Processes & Threads
- Explain what a process and a thread own, and what a context switch actually costs
- Describe the Linux address-space layout and how
fork/exec/copy-on-write work - Map Go's GMP scheduler onto kernel threads and explain why goroutines are cheap
- Reason about syscalls, signals and process states when debugging production services
- Design graceful shutdown for a payment service running as PID 1 in a Kubernetes pod
TL;DR
- A process is an isolated address space plus resources (file descriptors, credentials, signal handlers); a thread is a schedulable execution context inside it. On Linux both are
task_structs created byclone()with different sharing flags. fork()is cheap because of copy-on-write, but its cost still grows with page-table size; memory can balloon when the child or parent writes heavily (RedisBGSAVE).- A thread context switch costs roughly microseconds once cache/TLB effects are included; a goroutine switch is roughly 10× cheaper because it stays in user space.
- Go uses M:N scheduling (GMP): many goroutines (G) multiplexed onto OS threads (M) through logical processors (P, count =
GOMAXPROCS). Network I/O parks goroutines on the netpoller; blocking syscalls hand the P to another thread. - Syscalls are the boundary between your code and the kernel; each one is a mode switch, so batching (bigger buffers,
writev, fewer small writes) matters at high QPS. - SIGTERM is a request, SIGKILL is not. In Kubernetes you get SIGTERM, then SIGKILL after
terminationGracePeriodSeconds(default 30 s). Exit code 137 = killed by SIGKILL (often OOM), 143 = SIGTERM.
Why it matters
Consider a bank's transfer API during a rolling deploy at 10:00 on payday. Each old pod gets SIGTERM while it still has in-flight transfers that have debited one account but not yet published the credit event. If the process ignores the signal (because a shell wrapper is PID 1 and never forwards it) the kubelet SIGKILLs it 30 seconds later, mid-transaction. Your idempotency and outbox design (see Transactional Outbox & CDC) saves correctness, but customers still see timeouts, and reconciliation has work to do.
On the e-commerce side, a flash-sale checkout service that uses one OS thread per request runs out of memory or drowns in context switches long before the CPU is busy. Go's goroutine model avoids this, but only if you understand when the runtime does create extra threads (blocking syscalls, cgo, disk I/O) and how GOMAXPROCS interacts with container CPU limits.
Interviewers ask "process vs thread" to check fundamentals, then push on: why goroutines are cheaper, what happens on fork, how you would shut down safely, and what exit code 137 means. These are everyday production questions.
Core concepts
Process vs thread
| Resource | Shared between threads of one process? | Notes |
|---|---|---|
| Virtual address space (code, heap, globals, mmaps) | Yes | This is why threads can race on memory |
| Stack | No — one per thread | Linux default 8 MiB virtual for pthreads; only touched pages are resident |
| Registers, program counter | No | Saved/restored on context switch |
| File descriptor table | Yes | Closing an fd in one thread closes it for all |
| Signal handlers | Yes | Signal masks are per thread |
| PID | Shared TGID | Each thread has its own TID; getpid() returns the TGID |
| Credentials, cwd, rlimits | Yes (by default) |
Linux has no separate "thread" object. fork() and pthread_create() both end up in clone(). A thread is a task created with CLONE_VM | CLONE_FILES | CLONE_FS | CLONE_SIGHAND | CLONE_THREAD; a process is a task that shares (almost) nothing. That is also how containers work: clone() with CLONE_NEW* flags puts the new task in new namespaces (see Linux Containers).
You can see threads directly: ls /proc/$(pgrep myservice)/task lists one directory per thread, and ps -T -p PID shows them with their TIDs.
Address space layout
Every process sees a private virtual address space. On x86-64 with 4-level paging, user space is 128 TiB (47 bits); the kernel lives in the upper half and is unreachable from user mode.
Notes that matter in practice:
- Go does not use
brk. The runtime reserves heap arenas withmmapand manages them itself; goroutine stacks are also allocated from runtime-managed memory, not from per-thread OS stacks. - ASLR randomises the base addresses, which is why stack traces from
perfneed symbolisation per process. - VSZ vs RSS: virtual size counts reserved address space (Go binaries often show large VSZ); resident set size counts pages actually in RAM. Alert on RSS and cgroup memory, never VSZ. Details in Memory Management.
fork, exec, wait — and copy-on-write
The Unix process model is two calls: fork() duplicates the caller, exec() replaces the current program image with a new binary. The parent wait()s to collect the child's exit status.
- Copy-on-write (COW):
fork()does not copy memory. It copies page tables and marks all writable pages read-only in both processes. The first write to a page triggers a page fault and the kernel copies just that page. - fork is not free: copying page tables for a 30 GiB process takes noticeable time (tens to hundreds of milliseconds, roughly) and the parent is paused. Redis logs this as
latest_fork_usec. During a heavy write workload, COW can double resident memory in the worst case — the reason Redis docs recommendvm.overcommit_memory = 1and disabling transparent huge pages (a 2 MiB COW copy per 1-byte write). - exec closes
O_CLOEXECdescriptors. Go opens every fd with close-on-exec, so children launched withos/execdo not inherit your database sockets by accident. - Go never exposes plain
fork(). Forking a multi-threaded runtime would leave the child with one thread and locks possibly held by threads that no longer exist.os/execuses a combined fork+exec path (on Linux avfork-styleclone) so the child immediately becomes another program.
Process states
R(runnable/running),S(interruptible sleep — most idle server threads),D(uninterruptible, usually disk or NFS I/O; cannot be killed until the I/O returns),Z(zombie: exited, waiting for the parent to reap it).- Tasks in
Dcount toward Linux load average, which is why a hung NFS mount gives a load of 200 on an idle box (see CPU Scheduling). - Zombies and orphans: an orphaned child is re-parented to PID 1 (or the nearest "subreaper"). PID 1 must call
wait()on them, or zombies accumulate and eventually exhaust the PID limit. In a container your process may be PID 1.
Kernel threads vs user threads
| Model | Mapping | Examples | Trade-off |
|---|---|---|---|
| 1:1 | One user thread per kernel thread | Linux NPTL pthreads, classic Java threads | Simple and truly parallel, but each thread costs a kernel task, a large stack and kernel-mediated switches |
| N:1 | Many user threads on one kernel thread | Early green threads, single-threaded event loops | Very cheap switches, but no parallelism and one blocking syscall stalls everything |
| M:N | Many user threads on a pool of kernel threads | Go goroutines, Erlang processes, Java virtual threads (Java 21+) | Cheap and parallel, but the runtime must handle blocking syscalls, preemption and fairness itself |
Go's GMP model
- G — a goroutine: a small struct plus a growable stack (minimum 2 KiB; since Go 1.19 the runtime may start larger based on observed average usage). Stacks grow by copying, up to 1 GB on 64-bit by default.
- M — a machine: an OS thread. The runtime creates them on demand; the default cap is 10,000 (
debug.SetMaxThreads), and exceeding it crashes the program. - P — a logical processor that holds a local run queue (up to 256 Gs plus a
runnextslot) and the memory-allocator cache. ExactlyGOMAXPROCSPs exist, so at mostGOMAXPROCSgoroutines run Go code simultaneously.
How it behaves:
- Scheduling decisions happen in user space. When a goroutine blocks on a channel, mutex or network read, the runtime parks it and runs another G on the same M — no kernel involvement, so a switch costs on the order of a hundred nanoseconds (rough).
- Network I/O goes through the netpoller: sockets are non-blocking; on
EAGAINthe goroutine parks and epoll wakes it later. Thousands of idle connections cost goroutine stacks and buffers, not threads. See I/O Models. - Blocking syscalls (file reads,
fsync, cgo calls) block the M. The runtime detaches the P; if the syscall lasts longer than roughly 20 µs, thesysmonbackground thread hands the P to another M so other goroutines keep running. This is why disk-heavy Go programs show many threads. - Work stealing: an idle P steals half the run queue of a busy P; the global queue is checked periodically for fairness.
- Preemption: since Go 1.14 the runtime can asynchronously preempt a goroutine in a tight loop by sending its thread a signal (
SIGURG). Before that, a loop without function calls could stall GC.
Deep dive on the Go side: Goroutines & Channels.
Context switch cost
A kernel context switch saves registers, switches kernel stacks, possibly switches page tables (process switch), and runs scheduler logic. The direct cost is roughly 1–2 µs on modern hardware; the indirect cost — cold L1/L2 caches, TLB misses after switching address spaces, branch predictor pollution — often dominates and depends on working-set size. Threads of the same process skip the page-table switch, so they are cheaper than process switches.
Signals of trouble: vmstat 1 showing hundreds of thousands of cs per second, pidstat -w showing high nvcswch/s (involuntary switches = preempted while still wanting CPU, typical of CPU throttling or oversubscription).
System calls
A syscall is a controlled entry into the kernel: arguments go in registers, the syscall instruction switches to kernel mode, the kernel validates and runs the handler, then returns a value or -errno.
- A trivial syscall costs on the order of 100 ns to a few hundred ns; Meltdown mitigations (KPTI) made syscall-heavy workloads noticeably slower on affected CPUs.
- vDSO:
clock_gettimeandgettimeofdayare served from a kernel-provided page mapped into your process, sotime.Now()in Go usually does not enter the kernel. - Practical lesson: writing a log line or a response in many small
write()calls multiplies syscalls. Usebufio.Writer, batch Kafka messages, and preferwritev-style APIs (Go'snet.Buffers).
Signals
| Signal | Number | Catchable | Typical meaning for a service |
|---|---|---|---|
| SIGTERM | 15 | Yes | "Please shut down" — Kubernetes, systemd, docker stop |
| SIGINT | 2 | Yes | Ctrl-C in a terminal |
| SIGKILL | 9 | No | Immediate death: grace period expired or OOM killer |
| SIGHUP | 1 | Yes | Often "reload config" by convention |
| SIGQUIT | 3 | Yes | Go's default handler dumps all goroutine stacks and exits — handy for hung processes |
| SIGPIPE | 13 | Yes | Write to a closed pipe/socket; Go returns EPIPE for sockets instead of dying |
| SIGCHLD | 17 | Yes | A child changed state; the parent should wait() |
Exit codes above 128 mean "killed by signal (code − 128)": 137 = SIGKILL, 143 = SIGTERM. Kubernetes shows OOMKilled when the 137 came from the memory cgroup.
PID 1 is special. Inside a PID namespace the kernel does not apply the default action of a signal to PID 1 unless PID 1 installed a handler. The Go runtime installs handlers, so a Go binary as PID 1 exits on SIGTERM — but if your Dockerfile uses the shell form (ENTRYPOINT ./app instead of ENTRYPOINT ["./app"]), /bin/sh becomes PID 1 and does not forward signals. Your app never hears SIGTERM and is SIGKILLed after the grace period. Use the exec form, or a tiny init such as tini (docker run --init) when you spawn child processes that need reaping.
Graceful shutdown in Kubernetes
Endpoint removal is asynchronous, so for a few seconds after SIGTERM, traffic may still arrive. A short preStop sleep (or a sleep at the start of your shutdown handler) lets load balancers catch up before you stop accepting connections. The grace period includes the preStop time.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Multi-process (prefork, one process per worker) | Strong isolation; a crash or memory leak kills one worker; simple mental model | Higher memory per worker; IPC needed to share state; fork cost | Languages with a GIL (Python, Ruby), or untrusted plugins |
| Thread-per-request (1:1) | Straightforward blocking code; true parallelism | Memory and scheduler overhead at thousands of concurrent requests; context-switch heavy | Moderate concurrency, CPU-bound work, legacy Java/C++ services |
| Goroutines / virtual threads (M:N) | Blocking-style code with event-loop scalability; cheap creation | Runtime complexity; hidden thread creation on blocking syscalls/cgo; easy to leak goroutines | Most networked backend services — the Go default |
| Single-threaded event loop (N:1) | No locks; very predictable; low memory | One slow callback stalls everything; needs multiple processes for multi-core | Redis-style in-memory servers, proxies, Node.js |
In practice
A graceful shutdown skeleton for an HTTP service:
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %v", err)
}
}()
<-ctx.Done()
stop() // restore default handling: a second SIGTERM kills immediately
log.Println("SIGTERM received, draining")
// Let endpoint removal propagate before refusing new connections.
time.Sleep(5 * time.Second)
shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("forced shutdown: %v", err)
}
// Then: stop Kafka consumers (commit offsets), flush producers, close DB pools.
}
Budget the timeline explicitly: 5 s propagation + 20 s drain must fit within terminationGracePeriodSeconds (30 s default) with margin. For long-running work (batch settlement jobs, Kafka consumers mid-batch) either raise the grace period or make the work resumable and idempotent.
Useful inspection commands:
# Threads of a process and their states
ps -L -o pid,tid,stat,comm -p "$(pgrep -n payments)"
# Voluntary vs involuntary context switches per thread
pidstat -wt -p "$(pgrep -n payments)" 1
# Signal masks and handlers (SigCgt = caught signals bitmap)
grep -E 'Threads|SigCgt|voluntary' /proc/"$(pgrep -n payments)"/status
# Dump goroutine stacks of a hung Go process (it will exit afterwards)
kill -QUIT "$(pgrep -n payments)"
Rough numbers to keep in your head (all approximate, hardware-dependent): goroutine creation ≈ sub-microsecond and a few KiB; OS thread creation ≈ tens of microseconds and a kernel task plus stack; kernel context switch ≈ 1–5 µs including cache effects; trivial syscall ≈ 0.1–0.5 µs.
Common pitfalls
- Shell-form ENTRYPOINT.
shis PID 1, SIGTERM never reaches the app, every deploy ends in SIGKILL after 30 s and in-flight requests fail. Symptom: deploys are slow and logs never show "shutting down". - No drain delay. The app stops accepting connections the instant it gets SIGTERM while the load balancer still routes to it. Symptom: a burst of 502/503 on every rollout.
- Goroutine leaks. Goroutines blocked forever on a channel or a missing
ctxcancellation. Symptom: goroutine count and RSS climb steadily;/debug/pprof/goroutineshows thousands parked on the same line. - Thread explosion from blocking calls. Thousands of goroutines doing synchronous file I/O or slow cgo calls each pin an M. Symptom:
runtime: program exceeds 10000-thread limitor high memory with low heap usage. - Zombie accumulation. A service that shells out (
execofopenssl,pg_dump) as PID 1 and leaks grandchildren. Symptom:psshowsZentries; eventuallyfork: retry: Resource temporarily unavailableoncepids.maxis hit. - Forking a large process. Snapshotting (Redis
BGSAVE, some backup agents) on a 50 GiB process with THP enabled causes latency spikes and memory blow-up. Symptom: p99 spikes aligned with snapshots; OOM kills during persistence. - Misreading exit code 137 as "the app crashed". It means SIGKILL — check
OOMKilledand grace-period expiry first.
Interview angle
- "Process vs thread?" A strong answer goes beyond "threads share memory": what exactly is shared (address space, fds, signal handlers) vs per-thread (stack, registers, signal mask), that Linux implements both via
clone(), and the cost implications (creation, switching, isolation). - "Why are goroutines cheaper than threads?" Small growable stacks, user-space scheduling (no kernel transition on park/unpark), and the netpoller turning blocking I/O into parked goroutines. Mention the caveats: blocking syscalls and cgo still consume threads;
GOMAXPROCSbounds parallelism. - Follow-ups to expect: what happens on
forkin a multi-threaded program; what COW is; how Go handles a goroutine stuck in a tight loop (async preemption); how you would design graceful shutdown; what 137 vs 143 means. - Red flags: saying threads have separate heaps; believing SIGKILL can be caught; not knowing that Kubernetes sends SIGTERM first; claiming goroutines map 1:1 to OS threads.
Self-check
1. A teammate says "threads are just lightweight processes on Linux". In what sense is that true, and what is the practical difference?
True in implementation: both are tasks created by clone(), scheduled identically by the kernel. The difference is the sharing flags: threads share the address space, file descriptor table and signal handlers; processes get their own (with COW memory). Practically, threads can race on shared memory and one thread's crash (e.g. a segfault) kills the whole process, while processes are isolated and need IPC to share data.
2. Why does Redis' BGSAVE sometimes double memory usage and cause latency spikes?
fork() copies page tables (pausing the parent for a time proportional to memory size) and then relies on copy-on-write. Every page the parent modifies during the snapshot gets duplicated. Under write-heavy load most pages may be touched, approaching 2× memory. With transparent huge pages, each small write copies 2 MiB instead of 4 KiB, making both memory growth and fault latency worse.
3. Walk through what the Go runtime does when a goroutine calls os.ReadFile on a slow network-attached disk.
Regular files are not pollable by epoll, so the read is a blocking syscall on the current M. The runtime marks the goroutine as in-syscall and detaches its P. If the syscall exceeds roughly 20 µs, sysmon hands the P to another (possibly new) M so other goroutines continue. When the read returns, the original M tries to reacquire a P; if none is free, the goroutine goes to a run queue and the M parks. Many concurrent slow reads therefore create many threads.
4. Your pods take exactly 30 seconds to terminate on every deploy and some requests fail. What do you check?
The 30 s matches the default grace period, so SIGTERM is probably not handled: check whether PID 1 is a shell (ps -o pid,comm inside the container), whether the Dockerfile uses shell-form ENTRYPOINT, and whether the app registers a SIGTERM handler. For the failed requests, check whether the app stops accepting before endpoints are removed (add a preStop or in-app drain delay) and whether Shutdown has a timeout shorter than the remaining grace period.
5. What is the difference between a voluntary and an involuntary context switch, and what does a high involuntary rate suggest?
Voluntary: the thread blocked (I/O, lock, sleep) and gave up the CPU. Involuntary: the scheduler preempted it while it was still runnable (time slice expired or a higher-priority task woke). A high involuntary rate suggests CPU contention — more runnable threads than CPUs, CFS quota throttling in a container, or a GOMAXPROCS larger than the CPU allowance.
6. Why does Go not provide a plain fork() call?
The Go runtime is always multi-threaded (scheduler threads, GC workers, sysmon). After fork(), only the calling thread exists in the child, but locks held by other threads at fork time remain locked forever, and runtime state is inconsistent. So Go only supports fork immediately followed by exec (os/exec, syscall.ForkExec), where the child replaces itself before touching runtime state.
7. A pod shows exit code 137 but Kubernetes does not say OOMKilled. What are the likely causes?
137 means SIGKILL. Without OOMKilled, likely causes are: the grace period expired after SIGTERM (the app did not exit in time), a liveness probe failure leading to a kill after the grace period, a manual kill -9, or a node-level OOM kill that hit a process inside the container but not the container's main cgroup event. Check events (kubectl describe pod), the previous container's logs, and dmesg on the node.
Exercise
Observe threads, goroutines and signals on a real Linux box (a VM or docker run --rm -it golang:1.25 works).
- Write a Go program that starts 10,000 goroutines that each
time.Sleep(time.Minute), plus one HTTP server withnet/http/pprofimported. Checkls /proc/PID/task | wc -l(thread count) and the goroutine count at/debug/pprof/goroutine?debug=1. Explain why threads stay in the low tens. - Change the goroutines to each
os.ReadFilea large file on a slow volume in a loop (or callsyscall.Syscallon a blockingreadfrom a FIFO with no writer). Watch the thread count climb and explain via the GMP handoff rule. - Add the graceful shutdown code above. Run it in a container twice: once with
ENTRYPOINT ["/app"], once withENTRYPOINT /app. Rundocker stopand time it; inspect the exit codes withdocker inspect -f '{{.State.ExitCode}}'. - Send
kill -QUITto the running program and read the goroutine dump.
Done looks like: a short note with thread counts for steps 1–2, stop times and exit codes for both ENTRYPOINT forms, and one sentence explaining each result.
Further reading
- Operating Systems: Three Easy Pieces (Arpaci-Dusseau) — chapters on processes, the process API and limited direct execution: https://pages.cs.wisc.edu/~remzi/OSTEP/
- The Linux Programming Interface — Michael Kerrisk (processes, signals, threads in depth)
- Dmitry Vyukov, "Scalable Go Scheduler Design Doc" (2012) — the original GMP proposal
- Go runtime source:
runtime/proc.goheader comment, which documents the scheduler design - Kubernetes docs, "Pod Lifecycle" — termination of pods: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
man 7 signal,man 2 clone: https://man7.org/linux/man-pages/man7/signal.7.html
Related
- Goroutines & Channels — the Go-level view of goroutines and scheduling
- Building Production Services — graceful shutdown, health checks, timeouts
- CPU Scheduling — how the kernel decides which thread runs, and CPU throttling
- Memory Management — virtual memory, COW faults, RSS vs VSZ
- I/O Models — the netpoller that makes goroutine-per-connection scale
- Linux Containers — PID namespaces and why PID 1 matters
- Cloud-Native, Kubernetes & Deployment Strategies — rolling updates and pod lifecycle
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).