Operating systems for backend engineers: kernel, system calls, processes and threads
The kernel and system calls, user mode and kernel mode, processes, threads and the PCB, context switches, the Linux scheduler, and how they show up in the JVM and in containers: 1:1 threads, virtual threads, CPU quotas, PID 1 and SIGTERM.
On this page
1. The problem
A pod uses 40% of its CPU limit, yet p99 occasionally gains 50–100 ms. The same week, every deploy fails 0.5% of requests with 502, and the log never shows "Commencing graceful shutdown".
2. Key idea
The kernel is the only part that touches hardware directly. Applications in user mode read files or send packets through system calls. Reading a file byte by byte without a buffer is one syscall per byte.
A process has its own memory; threads run inside it and share that memory. To Linux, a thread is a task_struct sharing page tables. top -H -p <pid> lists each thread.
| Symptom | Root cause | Check with |
|---|---|---|
| Load 40 on 8 cores, CPU idle | load includes tasks waiting on disk (D) |
vmstat 1 columns wa, b; iostat -x 1 |
unable to create native thread |
hit ulimit -u, pids.max, or out of virtual memory for stacks |
ls /proc/<pid>/task | wc -l |
| p99 up despite low usage | quota used up within the 100 ms period | nr_throttled in cpu.stat |
| Requests cut during deploys | Java isn't PID 1 and never gets SIGTERM | exit code 137 instead of 143 |
2.1 Why does a container get throttled?
limits.cpu: 1 means every 100 ms, all threads together get 100 ms of CPU. 8 threads on 8 cores burn the quota in 12.5 ms, then the whole container freezes for 87.5 ms. Usage is averaged per minute; the quota is counted per 100 ms.
| Choice | Use when | Don't use when |
|---|---|---|
| CPU limit | you must contain noisy neighbours on the node | latency-sensitive services with many parallel threads |
| CPU request only | API services needing a stable p99 | tight nodes needing hard isolation |
| Virtual threads | I/O-bound work | pure CPU work |
The JVM derives availableProcessors() from the quota (GC threads, ForkJoinPool); override with -XX:ActiveProcessorCount.
3. In practice
An exec-form Dockerfile: Java is PID 1.
FROM eclipse-temurin:21-jre
COPY app.jar /app/app.jar
# exec: Java replaces the shell as PID 1 and receives SIGTERM
ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar /app/app.jar"]Stopping a pod: SIGTERM to PID 1, wait terminationGracePeriodSeconds (30 s by default), then SIGKILL. Exit 143 is SIGTERM, 137 is SIGKILL. Spring Boot needs server.shutdown=graceful. To count a process's syscalls: strace -c -f -p <pid> (slows it badly, use briefly).
Context switches, the scheduler, and sequential versus interleaved
- A context switch saves the old thread's registers and loads the new one: 1–5 µs directly, more indirectly because caches and the TLB go cold. Switching processes also swaps page tables.
- Many voluntary switches (yielding for I/O or locks) signal waiting; many involuntary ones (time slice used up) signal too many threads for the cores, or quota throttling.
- Since Linux 6.6 the scheduler is EEVDF (CFS before that): fair sharing in time slices of a few ms, plus virtual deadlines for latency-sensitive tasks.
- Pure CPU work on 1 core: 16 interleaved jobs finish the first one after ~450 ms instead of ~50 ms, averaging ~800 ms instead of ~440 ms. With I/O waits or fairness needs, interleaving wins. Don't put CPU-bound and I/O-bound work in the same pool.
System.nanoTime()usually doesn't enter the kernel thanks to the vDSO (~20 ns), except on some VMs whose clocksource doesn't support it.
4. Working with AI
Hand to AI: Dockerfiles, Kubernetes manifests, summarising vmstat output and thread dumps.
Check in AI-written code:
-
ENTRYPOINTis exec form or usesexec; Java is PID 1. -
server.shutdown=gracefulis set and the grace period exceeds the shutdown time. - Latency-sensitive services have no tight CPU limit, or
nr_throttledhas been checked. - Thread counts are bounded; no new thread per request.
5. Exercises
Exercise 1: Review a Dockerfile
The AI wrote the Dockerfile below, calling it "standard, with JAVA_OPTS". Every deploy, ~0.5% of requests fail with 502 and the log never shows "Commencing graceful shutdown". Why, and how do you fix it?
FROM eclipse-temurin:21-jre
COPY app.jar /app/app.jar
ENTRYPOINT java $JAVA_OPTS -jar /app/app.jarSolution to Exercise 1
Shell form makes /bin/sh -c PID 1; sh doesn't forward SIGTERM to Java, Spring never shuts down gracefully, and the pod is SIGKILLed after 30 seconds (exit 137).
Fix: ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar /app/app.jar"]. Add server.shutdown: graceful, spring.lifecycle.timeout-per-shutdown-phase: 20s, terminationGracePeriodSeconds: 40, and a preStop sleep 5, because removing the endpoint from the Service happens in parallel with SIGTERM.
Exercise 2: Read a high-load incident
An 8-core machine has load average 40, top shows 12% user CPU, vmstat 1 shows b = 30 and wa = 70. API p99 rises from 200 ms to 4 s. A colleague proposes adding 8 cores. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: Linux load counts tasks waiting on disk (
D).b= 30 andwa= 70 mean an I/O bottleneck, not a CPU shortage; more cores won't help. - 15 minutes:
iostat -x 1to find the disk at ~100%%utilwith highawait;iotoporpidstat -d 1to find the heavy writer (often log floods, backups, a hung NFS mount). Pause it. - Root fix: asynchronous logging or a lower log level, separate data and log disks, backups outside peak hours; alert on disk
await.
Summary
- A system call is a trap; only calling it too often hurts.
- A Linux thread is a task; platform threads are 1:1, virtual threads M:N.
unable to create native threadis an OS limit, not the heap.- High load with idle CPUs: look for disk bottlenecks.
- CPU quota is counted per 100 ms; Java must be PID 1 to receive SIGTERM.
Read more: Part 2: Virtual memory and the page cache.
Comments
Community rules