System Resource & I/O Optimization Questions
Tuning how a system uses CPU, memory, disk, and network at the OS and I/O layer. Covers I/O throughput and blocking, buffering and batching, filesystem and kernel-level performance settings, and resource contention between processes. Includes OS-level performance tuning and diagnosing resource saturation on the host.
Explain Transparent Huge Pages (THP) and how THP can impact performance for database or JVM workloads. Describe how to monitor THP usage, the pros and cons of enabling THP, and how to safely disable THP if it causes latency spikes.
Sample Answer
Direct answer
THP (Transparent Huge Pages) is a kernel feature that automatically backs a process's memory with large pages, typically 2 MB instead of the standard 4 KB, to cut down on the overhead of translating virtual addresses to physical ones. For most workloads that helps. For databases and JVM (Java Virtual Machine) processes with large, actively-changing heaps, THP's background compaction work can cause exactly the latency spikes it's meant to avoid, which is why most database vendors recommend disabling or restricting it.
Structured elaboration
Why huge pages help in principle. Every memory access goes through address translation, cached in the TLB (translation lookaside buffer, a small hardware cache mapping virtual addresses to physical ones). A 4 KB page can only cover 4 KB of address space per TLB entry, so a process with tens of gigabytes of memory generates constant TLB misses, each of which costs extra cycles to resolve via the page tables. A 2 MB page covers 512 times as much address space per entry (2,097,152 / 4,096 = 512), so the same memory footprint needs far fewer TLB entries, meaning fewer misses and faster memory access for large, contiguous-access workloads.
Why it hurts databases and JVMs in practice. THP in its default "always" mode uses a background kernel thread called khugepaged that continuously tries to find and defragment memory into huge-page-sized contiguous chunks. When memory is fragmented (common on long-running, memory-heavy processes with lots of allocation churn, like a JVM doing garbage collection or a database growing and shrinking its buffer pool), this compaction work can stall the requesting process synchronously while the kernel tries to assemble a contiguous 2 MB region, producing multi-millisecond to multi-second latency spikes at unpredictable times. There's also a memory-bloat effect: allocating a full 2 MB page when a process only needed a few KB wastes memory, and freeing partially-used huge pages is less efficient than freeing small ones.
Monitoring THP usage.
cat /sys/kernel/mm/transparent_hugepage/enabled: shows the current mode, with the active one in brackets, e.g.always [madvise] never.grep -i AnonHugePages /proc/meminfo: shows how much memory is currently backed by transparent huge pages.grep -i thp /proc/vmstat: fields likethp_fault_alloc(successful huge-page allocations),thp_collapse_alloc(pageskhugepagedmerged into huge pages), and importantlythp_fault_fallback(allocations that wanted a huge page but had to fall back to regular pages, often because compaction failed or stalled) are the strongest early signal of THP causing trouble.
Pros and cons. Pro: measurably faster memory access for workloads with large, relatively stable working sets and few small/short-lived allocations, since fewer TLB misses reduce CPU overhead per memory access. Con: background compaction (khugepaged) can introduce latency spikes under memory pressure or fragmentation, and huge pages can waste RAM for sparse or small allocations, both of which are common in database buffer pools and JVM heaps under GC churn.
Safely disabling THP. For an immediate, no-reboot change: echo never > /sys/kernel/mm/transparent_hugepage/enabled. This takes effect right away for new allocations. To persist it across reboots, add a systemd oneshot service (or a tuned profile) that writes that value at boot, or pass transparent_hugepage=never on the kernel command line. A middle ground many modern database vendors now recommend instead of a full disable is madvise mode, where THP is only used for memory regions an application explicitly opts into via the madvise() syscall, giving you the benefit for workloads that ask for it without the background compaction risk for everything else.
Worked example
On a MongoDB host showing occasional multi-second latency spikes uncorrelated with request volume, a baseline grep -i thp /proc/vmstat taken outside a spike might read:
thp_fault_alloc 48213
thp_fault_fallback 912
thp_collapse_alloc 3104
Sampling the same three counters again 30 seconds later, right as the next latency spike hits, might read:
thp_fault_alloc 48213
thp_fault_fallback 1187
thp_collapse_alloc 3402
thp_fault_alloc didn't move at all, but thp_fault_fallback jumped by 275 (1187 - 912) in that window: every huge-page allocation attempt during the spike failed and fell back to ordinary 4 KB pages. thp_collapse_alloc climbing by 298 (3402 - 3104) in the same window shows khugepaged was actively, and expensively, trying to compact fragmented memory into huge pages at the same moment. That correlation, not just the timing coincidence, is the smoking gun. Setting echo never > /sys/kernel/mm/transparent_hugepage/enabled and re-running the same load should hold both counters flat across an equivalent window; the remaining test is comparing p99 (99th percentile) latency before and after, for example a p99 that was 340ms with THP always dropping to roughly 60ms with THP never under the same load, to confirm the spikes tied to THP compaction are actually gone rather than assuming it worked from the sysctl change alone.
Trade-offs and pitfalls
Disabling THP entirely removes a real performance benefit for workloads that don't suffer from the compaction problem, so it's worth checking thp_fault_fallback before reaching for never rather than disabling it reflexively on every database host. The madvise middle ground is often the better default on current kernels precisely because it keeps the win for opted-in code paths while removing the background stall risk for everything else. Also remember that changing /sys/kernel/mm/transparent_hugepage/enabled directly is not persistent across reboots by itself; forgetting the persistence step is a common way this "fix" quietly reverts after the next kernel update or reboot.
Hard: You're paged for a production cluster where multiple services are intermittently getting killed by the OOM killer across nodes during peak load. Describe a step-by-step incident response plan to identify root cause, minimize user impact, and produce a remediation plan. Include commands, logs to check, short-term mitigations, and long-term fixes.
Sample Answer
Direct answer
Treat this as two parallel tracks: stop the bleeding (restore service quickly, even before root cause is understood) and find the actual memory pressure driver (a leak, a traffic spike, an undersized limit, or a co-located noisy neighbor) so the fix addresses the cause, not just the symptom. Out-of-memory (OOM) killer events across multiple nodes at once during peak load usually mean the pressure is systemic (a traffic-driven spike or a shared dependency), not one node's local misconfiguration.
Step-by-step incident response
Confirm and scope: check dmesg -T | grep -i "killed process" (the -T flag prints human-readable timestamps) and journalctl -k | grep -i oom on each affected node to get the exact process killed, its resident memory at time of death, and the timestamp; cross-reference which nodes and which services were hit to distinguish "one service misbehaving everywhere" from "many services on nodes that happen to be memory-pressured." Pull node-level memory metrics (Prometheus node_memory_MemAvailable_bytes or equivalent) around each kill timestamp to see whether available memory was trending down for minutes beforehand (a leak or gradual pressure buildup) or dropped suddenly (a spike, a burst allocation, or another process claiming memory fast).
Minimize user impact immediately: if a stateless service was killed, confirm its orchestrator (Kubernetes, systemd with Restart=) is actually restarting it and not crash-looping; if it is crash-looping because the memory pressure that killed it is still present, that node needs load shed (cordon it, drain remaining pods, stop new traffic routing to it) before the restart can succeed cleanly. If the killed process held state (a database, a cache) rather than being stateless, prioritize failover to a healthy replica over waiting for the killed instance to recover, since recovery time is unpredictable under continued memory pressure. Temporarily reduce load on affected nodes: shed non-critical batch/background work first (it is the cheapest thing to sacrifice), and consider scaling out horizontally to spread load across more, less-pressured nodes if capacity allows.
Root cause: for each killed process, check oom_score_adj (the per-process file at /proc/<pid>/oom_score_adj while it was alive, or the cgroup's, control group, the kernel mechanism that limits how much CPU/memory/I/O a group of processes can use, configured value) to understand why the kernel picked that process specifically, the OOM killer scores processes by memory usage adjusted by this value, so a process with a very negative oom_score_adj is protected and one with a positive value is preferentially killed. Check application-level memory metrics and, if available, a heap/memory profile from shortly before the kill to distinguish a genuine leak (steadily growing resident memory over hours/days) from a legitimate but under-provisioned peak-load spike (memory grows and would have stabilized if it had not been killed first). Check whether cgroup memory limits (memory.max for the process's cgroup) were set tighter than the process's actual peak-load working set, which would mean the kill was really a sizing problem, not a leak.
Remediation plan: short-term mitigations include raising the memory limit for the affected service if the root cause is legitimate peak-load sizing rather than a leak, and adding oom_score_adj protection for genuinely critical processes so a shared-host memory event kills a lower-priority process first. Long-term fixes include fixing the actual leak if one is confirmed (with a follow-up profiling task, not guessed at), right-sizing memory requests/limits based on real peak-load measurement rather than a guess, adding a memory-pressure early-warning alert (alerting on rising memory trend well before the OOM threshold, not only on the kill event itself, which is already too late), and considering systemd-oomd or a cgroup-aware OOM-avoidance daemon that can act earlier and more surgically than the kernel's blunt last-resort killer.
Commands and logs to check
dmesg -T, journalctl -k, /proc/<pid>/oom_score_adj (or the equivalent cgroup file), free -h and vmstat 1 for current memory state, Prometheus/Grafana (or equivalent) historical memory metrics per node and per process, and the application's own logs immediately before the kill for any sign of an unusual request pattern or a stuck operation holding memory.
Trade-offs and pitfalls
The most damaging mistake here is spending the first twenty minutes trying to find root cause instead of restoring service; on a multi-node, peak-load OOM event, mitigate first (load shed, failover, scale out) and investigate in parallel, not sequentially. A close second mistake is treating every OOM kill as a leak: many are legitimate peak-load sizing gaps that a leak-hunting investigation will not find, because there is nothing to find, the fix is capacity, not a bug fix.
A Kubernetes pod running a latency-sensitive service is being OOMKilled intermittently. Describe a step-by-step diagnostic approach (kubectl events, metrics, heap/profile dumps, sidecars) and remediation options (right-sizing, memory limits and requests, QoS classes, eviction tuning, and potential code fixes).
Sample Answer
Direct answer
Kubernetes pod OOM-kills come from two independent mechanisms that look identical from kubectl get pods, the container's own cgroup memory limit being hit (Kubernetes sets this from the pod's memory limit), or the node itself running out of memory and the kubelet evicting pods to relieve pressure, so the first diagnostic step is telling those two apart before reaching for a fix.
Diagnostic approach
kubectl describe pod <name> shows the last termination reason directly: OOMKilled with a specific container and exit code 137 (128 + signal 9, SIGKILL, which is exactly what the kernel's out-of-memory killer sends) confirms the container hit its own memory.max/limit, distinct from a node-level eviction, which shows up as pod status Evicted with a message about node memory pressure instead. kubectl get events --field-selector involvedObject.name=<pod> and cluster-wide events around the same timestamp help distinguish an isolated single-container limit breach from a wider node-pressure event affecting several pods at once. Pull the container's memory usage history from cluster metrics (kubectl top pod for a live snapshot, or Prometheus/cAdvisor-sourced history for the trend leading up to the kill) to see whether usage grew steadily (suggesting a leak) or spiked sharply (suggesting a burst, such as a large request payload or a batch operation). If the application exposes heap or memory profiling (a pprof endpoint for Go, a JVM heap dump trigger, Python's tracemalloc), capture a profile as close to the OOM event as possible, some runtimes support dumping a profile automatically on receipt of a specific signal or via a sidecar that polls memory and triggers a dump proactively before the kill happens, since a profile captured after the container has already restarted is too late. A sidecar container (or an init container writing periodic memory snapshots to a shared volume) is a common pattern specifically to capture that pre-kill state, since the killed container's own process is gone by the time anyone investigates.
Remediation options
Right-sizing: use the memory usage history gathered above to set resources.requests.memory and resources.limits.memory to reflect real peak usage plus headroom, rather than an initial guess; a Vertical Pod Autoscaler (if enabled) can suggest data-driven values from historical usage automatically. Memory limits and requests: setting requests meaningfully below limits (Burstable QoS) allows short bursts above baseline without immediately risking eviction, at the cost of the pod being evicted before a Guaranteed one under node-level pressure; setting them equal (Guaranteed QoS) protects the pod from node-pressure eviction but requires provisioning for peak, not average, usage. QoS classes: if this pod is genuinely latency-sensitive and important, moving it to Guaranteed QoS (requests == limits) protects it specifically from node-level eviction, though it does not protect it from hitting its own container-level memory.max if the limit itself is undersized. Eviction tuning: if node-level pressure (not the container's own limit) is the actual driver, review the kubelet's --eviction-hard/--eviction-soft thresholds and consider whether the node is simply overcommitted (too many pods' requests summed relative to real node capacity) rather than any single pod being at fault. Potential code fixes: if profiling confirms a genuine leak or an unbounded cache/buffer growing with load, the durable fix is in the application itself (bounding a cache, fixing a reference that prevents garbage collection, streaming instead of buffering a large payload), no amount of resource tuning fixes a true leak, it only delays the next kill.
Trade-offs and pitfalls
The most common misdiagnosis is treating every OOMKilled as "the limit was too low" and simply raising it without checking whether growth was actually unbounded; a genuine leak with a raised limit just takes longer to OOM again, it does not stop happening. Guaranteed QoS protects against node-pressure eviction but not against the container's own memory limit being hit, these are different protections and conflating them leaves a real gap. Capturing a profile close enough to the actual kill moment is the hardest and most frequently skipped step, since the process is gone the moment the kill happens, which is exactly why a proactive sidecar or scheduled snapshot approach matters more here than in a non-containerized incident.
Hard: On a NUMA system, a database exhibits poor performance after a kernel upgrade. Explain how NUMA misplacement can lead to this regression and provide a stepwise approach (commands and experiments) to detect and remediate NUMA-related memory allocation issues for the DB process.
Sample Answer
Mechanism: how a kernel upgrade breaks NUMA placement
NUMA (Non-Uniform Memory Access: each CPU socket has its own local memory, and reaching another socket's memory over the interconnect costs extra latency) placement is governed by kernel defaults that can change silently across an upgrade. Two common culprits: the default value of vm.zone_reclaim_mode (historically some distributions shipped it on by default on certain kernel versions, which prefers reclaiming local memory over allocating remote memory, and can end up thrashing the page cache instead of simply placing the allocation remotely) and automatic NUMA balancing (kernel.numa_balancing), the kernel's own background feature that migrates pages and threads toward each other over time, which can become more or less aggressive between kernel releases and add scanning overhead the database was not tuned to expect. Either change can quietly break a database's previously stable locality assumptions without anyone touching the database's own configuration.
Stepwise detection and remediation
- Confirm the regression is actually NUMA-related before chasing it: check
numastat -p <db_pid>now, and if a historical baseline exists, comparenuma_hit/numa_miss/other_nodebefore and after the upgrade. - Rule out a hardware or firmware change at the same maintenance window:
numactl --hardwareshould show the same topology as before; if BIOS NUMA interleaving settings were also touched during the same maintenance, that is a competing explanation worth ruling out first. - Diff the relevant sysctls against a known-good baseline:
sysctl kernel.numa_balancing,sysctl vm.zone_reclaim_mode, andcat /sys/kernel/mm/numa_balancing. A silent default change here is the most common root cause for this exact symptom (regression right after an otherwise routine kernel upgrade). - Confirm the database's CPU affinity mask is still actually applied:
taskset -pc <pid>. An upgrade to the init system or container runtime can drop an affinity setting that used to be set at boot without any visible error. - Run a controlled experiment: force strict locality on a canary instance with
numactl --cpunodebind=N --membind=Naround the database's startup, and measure whether latency recovers. This isolates whether placement is genuinely the cause versus something else that coincidentally changed with the kernel. - If automatic NUMA balancing overhead is the culprit, look for elevated
numa_pages_migratedin/proc/vmstatalongside CPU time in kernel migration threads; disable it (echo 0 > /proc/sys/kernel/numa_balancing) and re-pin statically instead, trading the kernel's adaptive behavior for a known-good fixed layout. - Make the fix durable: pin the database explicitly through the systemd unit (
AllowedCPUs=or anumactlwrapper) rather than relying on kernel defaults, and record the required sysctl values in configuration management so drift-detection catches the next kernel upgrade's default change before it pages someone.
Design resource-isolation and QoS policies for a multi-tenant Kubernetes cluster to prevent noisy-neighbor memory and I/O issues. Include admission controls, default resource requests/limits, QoS classes, eviction thresholds, node-level cgroup settings, and any custom controllers or webhooks you'd implement.
Sample Answer
Direct answer
Layer isolation at three points: admission (reject bad requests before they hit the scheduler), scheduling (requests/limits and Quality of Service, QoS, classes that determine who gets evicted first), and the node's cgroups (control groups, the Linux kernel mechanism that actually enforces CPU, memory, and I/O caps). Kubernetes wires the first two together well by default; the third, especially I/O isolation, has to be deliberately configured because the default cgroup setup only guarantees CPU and memory isolation well.
Design
Admission controls: a ResourceQuota per tenant namespace caps aggregate CPU, memory, and pod count for that tenant, so one team cannot schedule enough pods to starve everyone else regardless of per-pod limits. A LimitRange sets default and max/min requests-limits per container so a pod with no explicit resources still gets something sane. A validating/mutating admission webhook (built with Kyverno or OPA Gatekeeper, two common Kubernetes policy-engine tools that let you write custom admission rules without hand-rolling a webhook server; either works, pick whichever your team already runs, or a small custom one) enforces policy ResourceQuota cannot express: reject any pod with no memory limit at all, require requests == limits for anything labeled tier: critical, and block hostPath or privileged mounts that could let a tenant reach outside its cgroup.
Default requests/limits: set per-namespace defaults via LimitRange so a forgotten resource block does not silently become BestEffort. Size Guaranteed-tier requests near actual peak usage (not headroom), because Guaranteed requires requests == limits, so over-provisioning there is pure waste.
QoS classes: Kubernetes derives three classes from what you set. Guaranteed (every container's CPU and memory request equals its limit) is evicted last and gets the highest OOM-score protection. Burstable (requests below limits) is evicted before Guaranteed under memory pressure. BestEffort (no requests or limits set) is evicted first. Map workload tiers directly: latency-sensitive critical services get Guaranteed, standard services get Burstable, batch/background jobs get BestEffort or a low-priority Burstable capped hard by the batch namespace's ResourceQuota.
Eviction thresholds: the kubelet's --eviction-hard (e.g. memory.available<5%, nodefs.available<10%) triggers immediate, ungraceful eviction; --eviction-soft paired with --eviction-soft-grace-period gives pods time to shut down cleanly before the hard threshold is reached. Under pressure the kubelet evicts BestEffort pods first, then Burstable pods using more than their request, then Guaranteed pods only as a last resort. Pair this with PodDisruptionBudgets on critical services so an eviction sweep cannot take out every replica at once.
Node-level cgroup settings: run the kubelet with --cgroup-driver=systemd on cgroup v2 hosts so kubelet-managed limits (memory.max, memory.high, cpu.weight) land in the same unified hierarchy systemd itself uses, avoiding the split-brain that cgroup v1's cgroupfs/systemd mismatch used to cause. Enable --cpu-manager-policy=static and --memory-manager-policy=Static for Guaranteed, latency-sensitive pods that need exclusive, NUMA (non-uniform memory access: memory attached to one CPU socket is faster for that socket to reach than memory attached to another)-local cores. Kubernetes does not set I/O weights per QoS class by default, so add a small DaemonSet or node-init step that writes io.weight (or io.max for a hard IOPS, input/output operations per second, and throughput cap) under the BestEffort and Burstable kubepods.slice paths, so a batch job doing heavy disk writes cannot starve a critical pod's reads on the same disk.
Custom controllers/webhooks: the admission webhook above for policy enforcement, plus an optional lightweight controller that watches node-pressure metrics (node_memory_MemAvailable_bytes, node_disk_io_time_seconds_total) and proactively taints or cordons a node before the kubelet's own eviction kicks in, giving the scheduler time to steer new pods elsewhere instead of reacting after the fact.
Worked example
A 16-vCPU / 64GiB node runs three tenants. tier: critical gets Guaranteed pods at cpu: 2, memory: 4Gi (request equals limit). tier: standard gets Burstable pods at requests: {cpu: 250m, memory: 256Mi}, limits: {cpu: 1, memory: 512Mi}. tier: batch is capped at the namespace level by a ResourceQuota of limits.cpu: 8, limits.memory: 16Gi across the whole namespace, so even a misconfigured batch pod requesting cpu: 20 is rejected at admission, before the scheduler ever sees it. Eviction is set to --eviction-hard=memory.available<5% (about 3.2GiB free) and --eviction-soft=memory.available<10% with a 90-second grace period, so a batch memory leak gets 90 seconds to be killed gracefully before the node starts hard-evicting.
Trade-offs and pitfalls
Guaranteed QoS is expensive: since requests must equal limits, you provision for peak rather than average, which lowers bin-packing efficiency across the cluster. Static CPU/memory manager policies reserve whole cores per pod, which is even less flexible. Admission webhooks add request latency and become a new availability dependency for the cluster's control plane: decide explicitly whether the webhook fails open (a webhook outage lets unpoliced pods through) or fails closed (an outage blocks all pod creation), and monitor the webhook itself. The single most common gap is assuming requests/limits solve I/O isolation the same way they solve CPU/memory: cgroup v1's blkio controller is weak and cgroup v2's io controller must be explicitly wired to the kubepods hierarchy, or a BestEffort batch job doing sequential writes will still starve a Guaranteed pod's disk reads on the same device.
Unlock Full Question Bank
Get access to all System Resource & I/O Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.