CPU Scheduling
- Compare FCFS, SJF, round robin, priority and MLFQ scheduling on turnaround and response time
- Explain how Linux CFS (and its successor EEVDF) shares CPU using virtual runtime and weights
- Interpret run queue length, load average and PSI correctly, including inside containers
- Diagnose CFS quota throttling and size
GOMAXPROCSand CPU limits for latency-sensitive Go services
TL;DR
- Scheduling trades throughput, response time and fairness. SJF minimises average turnaround but needs job lengths; round robin gives good response time at the cost of context switches; MLFQ approximates SJF by learning from behaviour.
- Linux CFS (2.6.23–6.5) runs the task with the smallest virtual runtime; weights derived from
nicemake vruntime advance slower for high-priority tasks. Linux 6.6 replaced CFS with EEVDF, which adds per-task virtual deadlines for better latency control. Both are "the fair class" (SCHED_NORMAL). - Load average counts runnable and uninterruptible (D-state) tasks — compare it with the CPU count, and prefer per-CPU run queue (
vmstatr) and PSI (/proc/pressure/cpu) for saturation. - Container CPU limits are a quota per 100 ms period (
cpu.max). A multi-threaded process can burn the whole quota early in the period and then be throttled for the rest — tens of milliseconds of added latency with low average CPU. GOMAXPROCSmust match the CPU limit, not the node's core count. Go 1.25+ does this automatically from the cgroup limit; older versions needgo.uber.org/automaxprocsor an explicit env var.- CPU requests become relative weights (
cpu.weight); only limits cause throttling.
Why it matters
A card-authorisation service has a 150 ms budget end-to-end, including the call to the issuer. Its dashboard shows 30% average CPU, yet p99 latency jumps from 20 ms to 120 ms every few seconds. The cause is not slow code: the pod has a 2-CPU limit on a 32-core node, the Go runtime (pre-1.25) set GOMAXPROCS=32, and during GC bursts 32 threads exhaust the 200 ms-per-100 ms quota in about 6 ms. The kernel then freezes every thread in the container for the remaining ~94 ms of the period. Average CPU stays low; tail latency explodes.
The same mechanics show up during an e-commerce flash sale, when every checkout pod is CPU-hot simultaneously: throttling turns a capacity problem into a latency cliff, and retries from upstream make it worse. Knowing how the scheduler and cgroups interact lets you choose limits, GOMAXPROCS and autoscaling signals deliberately rather than by copy-paste from a Helm chart.
Core concepts
Goals and metrics
- Turnaround time = completion − arrival (batch jobs, settlement runs).
- Response time = first run − arrival (interactive, API requests).
- Throughput = jobs per unit time; fairness = no task starves.
- Preemptive schedulers can interrupt a running task (timer interrupt); non-preemptive ones wait for it to block or finish.
Classic algorithms
Worked example — three jobs arrive at t = 0: A needs 100 ms, B 10 ms, C 10 ms.
| Algorithm | Order | Turnaround A / B / C | Average turnaround | Notes |
|---|---|---|---|---|
| FCFS (first come, first served) | A, B, C | 100 / 110 / 120 | 110 ms | Convoy effect: short jobs stuck behind a long one |
| SJF (shortest job first) | B, C, A | 120 / 10 / 20 | 50 ms | Optimal average turnaround for known lengths; long jobs can starve |
| SRTF (preemptive SJF) | Shortest remaining first | Same here | 50 ms | Handles late arrivals; still needs length estimates |
| Round robin, 10 ms quantum | A, B, C, A, A… | 120 / 20 / 30 | ≈ 57 ms | Good response time; worst turnaround for equal-length jobs; quantum vs switch-overhead trade-off |
| Priority | By priority | Depends | — | Starvation of low priority unless you add aging |
Quantum size is the core RR trade-off: too small and context switches eat the CPU; too large and RR degenerates to FCFS.
Multi-level feedback queue (MLFQ)
MLFQ approximates SJF without knowing job lengths by watching behaviour. OSTEP summarises it in a handful of rules:
- Higher-priority queue runs first; equal priority runs round robin.
- New jobs enter the top queue.
- A job that uses up its time allotment at a level is demoted (CPU-bound jobs sink).
- Periodically, boost all jobs to the top (prevents starvation and adapts to phase changes).
Interactive (I/O-bound) jobs stay high and get good response time; batch jobs sink and get long slices. Windows and older Unix schedulers used MLFQ variants; Linux moved to a fairness model instead.
Linux scheduling classes
| Class / policy | Use | Notes |
|---|---|---|
SCHED_DEADLINE | Hard periodic workloads (runtime, deadline, period) | Highest of the normal classes; admission control |
SCHED_FIFO, SCHED_RR | Real-time, priorities 1–99 | Always preempt fair tasks; by default RT tasks are limited to 95% of CPU time (sched_rt_runtime_us) to avoid lockups |
SCHED_NORMAL (SCHED_OTHER) | Everything else — your services | CFS, or EEVDF on 6.6+ |
SCHED_BATCH | CPU-bound background work | Fewer wake-up preemptions |
SCHED_IDLE | Only when nothing else wants the CPU | Even lower than nice 19 |
Linux 6.12 also added sched_ext, which lets you load a scheduling policy as a BPF program — mostly relevant to platform teams experimenting with custom schedulers.
CFS: fairness via virtual runtime
CFS models an "ideal multitasking CPU" where N runnable tasks each get 1/N of the CPU at every instant.
- Each task has a vruntime: actual runtime scaled by
1024 / weight. A nice-0 task's vruntime grows at wall speed; a heavier (higher-priority) task's grows slower, so it gets picked more often. - Runnable tasks sit in a red-black tree ordered by vruntime. The scheduler picks the leftmost (smallest vruntime) — O(1) with a cached pointer, O(log n) to insert.
- A task that sleeps does not accumulate vruntime; on wake-up it is placed near the current minimum so it cannot monopolise the CPU after a long sleep but gets to run soon — which is why I/O-bound services feel responsive.
- Slices are derived from a target latency (a few ms, scaled with CPU count) divided among runnable tasks, with a minimum granularity so slices do not become uselessly small.
Per-CPU run queues: each CPU has its own tree. Periodic and idle-time load balancing migrates tasks between CPUs, respecting cache and NUMA topology (scheduling domains). Migration is not free: a task moved across NUMA nodes loses cache warmth and may access remote memory.
EEVDF (Linux 6.6+)
EEVDF — Earliest Eligible Virtual Deadline First — keeps the fair-share idea but changes how the next task is chosen:
- Each task tracks lag: how much CPU it is owed versus its fair share. Only tasks with non-negative lag are eligible.
- Each eligible task gets a virtual deadline = eligible time + slice / weight. The scheduler runs the eligible task with the earliest deadline.
- A task with a shorter requested slice gets an earlier deadline, so latency-sensitive tasks can run sooner without receiving more total CPU. The user-facing interface for setting slices is still evolving across kernel versions.
For a service owner, the practical change is fewer ad-hoc heuristics and some old CFS tunables disappearing. Behaviour under contention is broadly similar; benchmark if you upgrade kernels on latency-critical nodes.
Nice values and weights
nice ranges from −20 (highest priority) to 19 (lowest). Nice 0 has weight 1024; each step changes weight by about 1.25×, which works out to roughly a 10% CPU-share difference between adjacent levels when two tasks compete.
Example: two CPU-bound tasks on one core, nice 0 (weight 1024) and nice 5 (weight 335) → shares ≈ 1024/1359 = 75% and 25%.
nice -n 10 ./nightly-reconciliation # start a batch job at lower priority
renice -n 5 -p 4321 # lower the priority of a running process
chrt -p 4321 # show scheduling policy and RT priority
ionice -c3 -p 4321 # idle I/O class (I/O scheduler permitting)
Inside containers, prefer cgroup weights (cpu.weight) to nice: nice only ranks tasks against each other, while cgroup weights rank whole groups.
CPU affinity and NUMA
- Affinity restricts which CPUs a thread may run on:
taskset -c 0-3 ./app,sched_setaffinity(2), or cgroup cpusets (cpuset.cpus). - Why pin: keep caches warm, avoid NUMA remote access, isolate noisy work (IRQs, GC) from latency-critical threads. Trading and matching engines (see Stock Exchange) pin threads to isolated cores (
isolcpus,nohz_full) and busy-poll. - Kubernetes: the kubelet CPU Manager
staticpolicy gives Guaranteed-QoS pods with integer CPU requests exclusive cores via cpusets. - Go: there is no per-goroutine affinity.
runtime.LockOSThreadwires a goroutine to its current thread (needed for thread-local OS state, some C libraries); you can then callunix.SchedSetaffinityon that thread.runtime.NumCPU()respects the affinity mask but not the CFS quota.
Run queue, load average and PSI
- Run queue length: tasks runnable on a CPU (running + waiting).
vmstat 1columnrshows the total; sustainedrabove the CPU count means CPU saturation. - Load average (
uptime,/proc/loadavg): exponentially damped 1-, 5- and 15-minute averages of runnable + uninterruptible (D) tasks. On Linux it measures demand on CPU and some I/O, so a load of 40 on an 8-core box might be CPU saturation or a stuck NFS mount. Brendan Gregg's article "Linux Load Averages: Solving the Mystery" explains the history. - PSI (pressure stall information, Linux 4.20+):
/proc/pressure/cpureports the share of time at least one task was waiting for CPU (some avg10=12.5means 12.5% over the last 10 s). Per-cgroup versions exist (cpu.pressure). PSI is the cleanest saturation signal. - Per-task:
/proc/PID/schedstatgives time on CPU, time waiting on the run queue, and timeslice count; bcc'srunqlatshows a histogram of run-queue wait. - In containers,
/proc/loadavgandnproctypically show host values. Use the container'scpu.statandcpu.pressureinstead.
CPU limits in containers: CFS bandwidth control
cgroup v2 expresses a limit as cpu.max = "QUOTA PERIOD" in microseconds. A Kubernetes limit of 2 becomes 200000 100000: up to 200 ms of CPU time per 100 ms period, summed across all threads in the cgroup.
Throttling example (pre-1.25 Go, GOMAXPROCS 32, limit 2 CPUs):
What you see: cpu.stat shows nr_throttled and throttled_usec climbing; average CPU usage ≤ 2 cores; p99 latency spikes by up to ~94 ms; involuntary context switches high.
cat /sys/fs/cgroup/cpu.max # e.g. "200000 100000"
cat /sys/fs/cgroup/cpu.stat # nr_periods, nr_throttled, throttled_usec
cat /sys/fs/cgroup/cpu.pressure # some/full avg10, avg60, avg300
Fixes, roughly in order of preference:
- Match
GOMAXPROCSto the limit. Go 1.25+ sets the default from the cgroup CPU limit and updates it if the limit changes (opt out withGODEBUG). On older Go, importgo.uber.org/automaxprocsor setGOMAXPROCSfrom the limit via the downward API. - Raise or remove the limit for latency-critical services, keeping requests accurate so the scheduler still places pods sensibly. Many platform teams run "requests, no CPU limits" for Go/Java services; others need limits for cost governance and noisy-neighbour control. Make it an explicit decision.
- Burst allowance:
cpu.max.burst(5.14+) lets a cgroup bank unused quota for short bursts; support in orchestration varies. - Older kernels (before roughly 5.4) had a bug that throttled even when quota was unused; upgrade if you see throttling at low utilisation on old nodes.
Why Go is especially sensitive: the garbage collector uses about 25% of GOMAXPROCS as dedicated mark workers, plus mark assists from allocating goroutines. With GOMAXPROCS=32 under a 2-CPU limit, a GC cycle alone can drain the quota.
Requests become weights
A CPU request is converted to a relative weight: in cgroup v1 cpu.shares = millicores × 1024 / 1000 (500m → 512), in cgroup v2 a cpu.weight derived from shares (with the classic linear conversion 1 CPU ≈ 39, while a plain cgroup defaults to 100; newer runtime versions have been moving to a conversion that maps 1 CPU closer to 100, so check your runc/crun version). Weights only matter when CPUs are contended: an idle node lets a pod use far more than its request (unless limited). See Linux Containers for the full mapping.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Requests + CPU limits (Burstable/Guaranteed) | Predictable cost and capacity; noisy neighbours contained | Throttling adds tail latency; must tune GOMAXPROCS and headroom | Shared multi-tenant clusters, batch, cost-capped teams |
| Requests, no CPU limits | Uses idle CPU, no throttling, best tail latency | A runaway pod can starve neighbours (only weights protect); less predictable capacity tests | Latency-critical APIs on well-managed clusters with good requests |
| Guaranteed + static CPU Manager (pinned cores) | Exclusive cores, warm caches, minimal jitter | Wastes capacity; integer CPUs only; operational complexity | Matching engines, low-latency payment switches, telco-style workloads |
nice / SCHED_BATCH / SCHED_IDLE | Cheap way to deprioritise batch on shared VMs | Only relative within the same cgroup; not isolation | Reconciliation or report jobs co-located with online services on VMs |
Real-time (SCHED_FIFO) | Bounded latency for critical threads | Can lock up the box if a thread spins; requires care | Rarely for business services — audio, networking appliances, trading |
In practice
Log the effective CPU environment at startup so incidents are easier to read:
package main
import (
"log"
"os"
"runtime"
"strconv"
"strings"
)
// cgroupCPULimit returns the cgroup v2 CPU limit in cores, if one is set.
func cgroupCPULimit() (float64, bool) {
b, err := os.ReadFile("/sys/fs/cgroup/cpu.max")
if err != nil {
return 0, false
}
fields := strings.Fields(string(b))
if len(fields) != 2 || fields[0] == "max" {
return 0, false
}
quota, err1 := strconv.ParseFloat(fields[0], 64)
period, err2 := strconv.ParseFloat(fields[1], 64)
if err1 != nil || err2 != nil || period == 0 {
return 0, false
}
return quota / period, true
}
func main() {
limit, ok := cgroupCPULimit()
log.Printf("NumCPU=%d GOMAXPROCS=%d cgroupLimit=%.2f limited=%v",
runtime.NumCPU(), runtime.GOMAXPROCS(0), limit, ok)
}
Alert on throttling, not just utilisation. With cAdvisor metrics in Prometheus:
# Fraction of periods in which the container was throttled
rate(container_cpu_cfs_throttled_periods_total[5m])
/ rate(container_cpu_cfs_periods_total[5m])
A sustained throttled-period ratio above a few percent on a latency-sensitive service is worth investigating.
Rules of thumb (approximate):
- Size CPU requests at p95 usage under normal peak, and leave enough limit headroom (or no limit) for GC and bursts.
- Autoscale on a signal that leads latency — request concurrency, queue depth or CPU request utilisation around 50–70% — rather than on throttled CPU, which caps out at the limit.
- On VMs, check
%stealinmpstat: a noisy neighbour on the hypervisor looks like your process being slow. - For batch jobs (end-of-day settlement, statement generation) co-located with online traffic, run them in a lower-weight cgroup or a separate node pool rather than relying on
nice.
Common pitfalls
GOMAXPROCS= node cores in a CPU-limited pod (Go below 1.25). Symptom: periodic p99 spikes, highnr_throttled, low average CPU.- Reading load average as CPU utilisation. A load of 16 on 8 cores may be D-state I/O waits. Symptom: "CPU is overloaded" conclusions while
mpstatshows idle CPUs; checkvmstatbcolumn andiostat. - Using
nprocorruntime.NumCPU()inside a container to size worker pools. Both ignore CFS quota, so a 1-CPU pod on a 64-core node starts 64 workers. Symptom: throttling and memory bloat. - Single hot CPU. One core at 100% (
mpstat -P ALL) while others idle: a single-threaded bottleneck, a mutex-serialised section, or all NIC interrupts landing on CPU 0 (fix with RSS/IRQ affinity). - Busy-spinning in user space under CPU limits: spinners burn quota while the lock holder is throttled. Symptom: high CPU, low throughput.
- Autoscaling on CPU when CPU is capped by limits. HPA sees "100% of limit" and scales, but per-pod latency is already broken by throttling; or worse, it never exceeds the threshold because throttling caps usage.
- Forgetting cross-NUMA effects on large bare-metal database hosts. Symptom: performance varies run to run;
numastatshows highother_nodeallocations.
Interview angle
- Classic question: "Compare scheduling algorithms" — give the SJF optimality result, the convoy effect, the RR quantum trade-off and starvation/aging; then pivot to how Linux actually does it (CFS/EEVDF, weights).
- Architect-level question: "Your service's p99 is bad but CPU is 30% — what do you check?" A strong answer mentions CFS throttling (
cpu.stat),GOMAXPROCSvs limits, run-queue latency (runqlat, PSI), GC, and off-CPU waits (locks, I/O, downstreams). - "Should we set CPU limits?" — expected to articulate both sides (isolation and cost vs throttling and tail latency) and give a policy (e.g. limits for batch and untrusted tenants, no limits but accurate requests for critical APIs, Guaranteed pinned cores for the matching engine).
- Follow-ups: what load average actually counts; how nice maps to CPU share; how Kubernetes converts requests to weights; what changed with EEVDF.
- Red flags: "load average = CPU %"; "requests limit CPU usage"; not knowing that throttling exists.
Self-check
1. Why does SJF minimise average turnaround time, and why is it impractical as-is?
Running the shortest job first means fewer jobs wait behind long ones — any swap that puts a longer job earlier increases the total waiting time. It is impractical because the scheduler rarely knows job lengths in advance, and long jobs can starve. MLFQ approximates SJF by inferring "short" from observed behaviour.
2. In CFS, two CPU-bound tasks compete for one core, one at nice 0 and one at nice 5. Roughly what share does each get, and why?
About 75% and 25%. Nice 0 has weight 1024, nice 5 has weight 335; CFS distributes CPU in proportion to weight because vruntime advances at a rate inversely proportional to weight, and the scheduler keeps vruntimes balanced.
3. A pod has cpu.max = 100000 100000 and the Go runtime runs 8 busy threads. Describe what happens within one period.
The limit is 100 ms of CPU per 100 ms period. Eight busy threads consume it in about 12.5 ms of wall time. The cgroup is then throttled — none of its threads run — for the remaining ~87.5 ms. Requests that arrive or are in flight during that window wait, adding up to ~87 ms latency. nr_throttled increments for that period.
4. Load average on an 8-core host is 30 but mpstat shows 70% idle. What is going on?
Linux load average includes tasks in uninterruptible sleep (D state), typically waiting on disk or network filesystems. Many threads blocked on slow I/O inflate load without using CPU. Check vmstat (b column), ps -eo stat,comm for D-state tasks, iostat -xz and dmesg for storage problems.
5. Why can runtime.NumCPU() be misleading in a container, and what does Go 1.25 change?
NumCPU reports CPUs in the affinity mask (cpuset), not the CFS quota, so a pod limited to 2 CPUs on a 64-core node sees 64. Before Go 1.25, GOMAXPROCS defaulted to that value. Go 1.25 makes the default GOMAXPROCS respect the cgroup CPU limit and adjust if it changes; NumCPU itself still reports the affinity count.
6. Scenario: a bank's fraud-scoring service must answer within 50 ms at p99.9 and runs next to batch ML feature jobs on the same cluster. How would you configure CPU?
Give the scoring pods accurate requests and either no CPU limit or a generous one with GOMAXPROCS aligned; consider Guaranteed QoS with the static CPU Manager for exclusive cores if jitter matters. Put batch jobs in a separate node pool or give them limits and lower weights so they cannot steal CPU. Monitor throttled-period ratio, PSI and run-queue latency, and autoscale scoring on concurrency or latency rather than raw CPU.
7. What is the difference between EEVDF and CFS in one or two sentences?
Both share CPU in proportion to weight. CFS picks the task with the smallest vruntime; EEVDF picks, among tasks that are owed CPU (non-negative lag), the one with the earliest virtual deadline, which lets tasks with short slices get lower latency without getting more CPU overall.
Exercise
Reproduce CFS throttling and measure its latency impact.
- Write a Go program that: (a) starts N goroutines doing CPU work in a loop (e.g. hashing a buffer with
crypto/sha256), and (b) in another goroutine, runs atime.Tickerat 1 ms and records how late each tick fires (time.Since(expected)) into a histogram; print p50/p99/max every 5 s. - Run it in Docker with
--cpus=1and N = 8, first withGOMAXPROCS=8, thenGOMAXPROCS=1. If you have Go 1.25+, also run with noGOMAXPROCSset and withGODEBUG=updatemaxprocs=0,containermaxprocs=0to compare against the old default. - During each run, read
/sys/fs/cgroup/cpu.statinside the container before and after, and compute the throttled-period ratio. - Bonus: run
perf sched latencyor bccrunqlaton the host while the test runs.
Done looks like: a table with GOMAXPROCS setting, throttled ratio, tick-lateness p99 and max, and a two-sentence explanation of why they differ.
Further reading
- Operating Systems: Three Easy Pieces — chapters "Scheduling: Introduction", "The Multi-Level Feedback Queue", "Lottery Scheduling": https://pages.cs.wisc.edu/~remzi/OSTEP/
- Brendan Gregg, Systems Performance (2nd ed., 2020) — CPU chapter, scheduler latency and methodology
- Brendan Gregg, "Linux Load Averages: Solving the Mystery" (2017)
- Linux kernel documentation, "CFS Scheduler" and "Control Group v2" (cpu controller): https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
- Kubernetes docs, "Resource Management for Pods and Containers": https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
- Go 1.25 release notes (container-aware
GOMAXPROCS): https://go.dev/doc/go1.25
Related
- Processes & Threads — what the scheduler is scheduling, and Go's GMP model
- Linux Containers — cgroups v2 controllers and Kubernetes resource mapping
- Linux Performance Analysis —
mpstat,pidstat,runqlat,perf sched - Profiling & Performance — finding where Go CPU time goes
- Capacity Planning & Cost — sizing requests, limits and headroom
- Cloud-Native, Kubernetes & Deployment Strategies — autoscaling and QoS classes
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).