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.
At the kernel level, what commonly causes spikes in context-switch rates? Describe kernel parameters or user-space strategies to reduce context switching, including thread models, futex usage, lock contention, and potential side effects of scheduler changes.
Sample Answer
What commonly causes context-switch spikes
A context switch is the kernel saving one thread's execution state and loading another's onto the CPU. Spikes fall into two broad categories with different root causes.
Voluntary switches happen when a thread blocks itself, most often on I/O or a lock. A spike here usually means increased lock contention: many threads repeatedly fighting over the same mutex, each one blocking (switching out) and later waking (switching back in) as the lock changes hands, rather than any kernel defect.
Involuntary switches happen when the scheduler preempts a running thread because its timeslice expired or a higher-priority task became runnable. A spike here usually means CPU oversubscription, for example a thread pool sized far above the actual core count, or a burst of higher-priority work (interrupts, real-time tasks) repeatedly preempting normal ones.
futex and lock contention specifically
futex (fast userspace mutex, the primitive underneath most language runtimes' Mutex/Lock types on Linux) has a fast path that never touches the kernel at all: an uncontended lock/unlock is a pure userspace atomic compare-and-swap, no context switch involved. Contention is what turns it expensive: the losing thread calls into the futex() syscall to sleep (one context switch out) and is later woken (another context switch in). A high context-switch count alongside elevated sys CPU time and a rising syscalls:sys_enter_futex rate (visible via perf stat -e syscalls:sys_enter_futex or strace -c) is a strong, specific signal that the spike is lock contention, not scheduler churn from something else.
Thread models
A thread-per-connection or thread-per-request model creates far more runnable threads than available cores under real concurrency, forcing heavy scheduler churn by design. Event-loop or async models use far fewer OS threads for the same concurrency, which reduces this class of context-switch pressure structurally rather than through any kernel tunable; that is a design decision, not a sysctl.
Kernel parameters and user-space strategies
- Bound thread-pool size near the core count (
nproc) for CPU-bound work instead of spawning an unbounded thread per request. kernel.sched_min_granularity_nsandkernel.sched_wakeup_granularity_ns(CFS scheduler tunables) control how eagerly the scheduler preempts a running task in favor of one that just woke up; raising them reduces preemption frequency at a real cost: added latency for whatever thread just became runnable and now waits longer.- CPU pinning and isolation (
isolcpus,taskset) give latency-critical threads dedicated cores with nothing else scheduled on them, eliminating involuntary switches from that core entirely. - Reducing lock granularity in the application itself (finer-grained locks, lock-free data structures, sharding a single contended structure into several) addresses the actual cause of voluntary-switch spikes and is usually the highest-leverage fix, since it removes the contention rather than just changing how the scheduler responds to it.
Side effects of scheduler changes
Any global sysctl change (widening scheduler granularity, for example) affects every workload on the host, not just the one you are trying to fix. On a multi-tenant host, reducing context switches for the target service by making the scheduler less preemptive can starve or add latency to OTHER services sharing that host. Always canary such a change and measure the OTHER workloads' latency, not just whether the target's context-switch count went down.
Compare O_DIRECT (direct I/O) and fsync-related durability semantics. How do they interact with filesystem buffering and device write caches (battery-backed or volatile), and what are the performance and correctness trade-offs for database systems?
Sample Answer
Direct answer
O_DIRECT and fsync solve different problems and are typically used together, not as alternatives. O_DIRECT is an open flag that bypasses the OS page cache so reads and writes go close to directly between the application's buffer and the storage device. fsync (and fdatasync) is a durability guarantee: it forces dirty data to actually reach persistent storage, including flushing past any volatile write cache the device itself maintains, regardless of whether O_DIRECT was used to get there. For database systems, both matter, and getting the interaction wrong is a real correctness risk, not just a performance nuance.
Structured elaboration
What each one actually does. Without O_DIRECT, a normal buffered write() call copies data into the page cache and returns immediately; the kernel's writeback threads flush it to the device asynchronously later. That write is not durable the instant it returns, only fsync provides that guarantee. O_DIRECT changes where the write goes, pushing it toward the device directly instead of parking it in the page cache first, but it does not by itself guarantee durability: the storage device can have its own volatile write cache that acknowledges the write as complete before the data has actually reached durable NAND or platter. fsync is what closes that gap: it issues a cache-flush (or FUA, force unit access, a write mode that bypasses the device's write cache entirely) command to the device, so that even data sitting in a volatile on-device cache gets committed to durable media before fsync returns successfully.
Interaction with filesystem buffering and device write caches. Filesystem-level buffering (the page cache) is what O_DIRECT bypasses. Device-level write caches are a separate layer below that, and they come in two flavors that behave very differently: battery-backed write caches (common on enterprise RAID controllers) can safely acknowledge a write as durable before it physically reaches the storage medium, because the battery guarantees that cached data survives a power loss and gets flushed once power returns, so fsync against such a controller can return quickly without sacrificing durability. Volatile write caches with no battery backing are a correctness hazard if they don't honor flush commands properly: fsync can appear to succeed while the data is still sitting in a cache that a power loss would wipe out, which is why production database deployments either disable volatile write caches outright, rely on FUA writes, or explicitly verify that the storage stack correctly honors flush/barrier commands rather than assuming it does.
Performance and correctness trade-offs for database systems. O_DIRECT's benefit is avoiding double buffering: without it, the same data can end up cached twice, once in the OS page cache and again in the database's own buffer pool, wasting RAM and an extra memory copy for no benefit, since the database's own cache eviction policy is usually better tuned to its actual access patterns than the kernel's generic one. The cost is that the database now has to implement its own readahead, write coalescing, and I/O scheduling, work the OS page cache would otherwise have done for free. fsync, separately, is what actually provides the durability guarantee (the "D" in ACID, atomicity, consistency, isolation, durability, the standard correctness properties a transactional database aims to guarantee) regardless of whether O_DIRECT is in play. The trade-off there is pure latency versus durability risk: calling fsync on every single transaction commit is safe but bounded by the device's flush latency, so many systems batch multiple transaction commits together and call fsync once per batch (commonly called group commit) to amortize that cost across several transactions, and some deployments knowingly relax this further (an async or deferred commit mode) to gain throughput at the explicit cost of being able to lose the most recent commits if the system crashes before the next flush.
Worked example
A database using O_DIRECT for its data files avoids caching the same pages twice, but if its write-ahead log (WAL, a sequential record of every change written before the change is applied, used to recover after a crash) is written with O_DIRECT alone and no fsync at commit time, a crash immediately after a transaction reports success can still lose that transaction, because O_DIRECT only changed where the write went, not whether it durably landed past every cache layer. Adding fsync (or opening the WAL with O_DSYNC, which folds an fdatasync-equivalent guarantee, the data plus only the metadata needed to read it back, into every write call; the stronger O_SYNC is the one that matches fsync's full guarantee, including metadata like mtime that a WAL commit doesn't actually need) at each commit point closes that gap. If commit-time fsync latency becomes the throughput bottleneck, group commit, batching several transactions into one fsync call, is the standard fix that keeps the same durability guarantee per committed batch while amortizing the flush cost across more transactions than committing one at a time would allow.
Trade-offs and pitfalls
The most consequential mistake is assuming O_DIRECT alone provides durability; it does not, it only changes where data goes, not whether it has actually reached persistent storage past every cache layer. A second common mistake is assuming any hardware write cache is safe to leave enabled without verifying it's actually battery-backed and correctly honoring flush commands; a volatile cache that silently ignores flushes will pass every functional test and then lose data on the first real power loss, precisely because the failure only shows up under a condition testing doesn't normally exercise.
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.
Explain CPU 'steal' time observed on VMs. What does it indicate about hypervisor scheduling behavior, how does it manifest to tenant workloads, and what steps can you take as an SRE to detect and mitigate steal across cloud hosts?
Sample Answer
What CPU steal time means
Steal time (the st field in top/vmstat, or steal in /proc/stat) is the fraction of a sampling interval during which a guest VM's virtual CPU wanted to run but the hypervisor scheduled a different tenant's virtual CPU on the physical core instead. It only exists in virtualized environments: the guest kernel has no direct control over, or even visibility into, why it did not get the core, only that it did not.
What it indicates about hypervisor scheduling
Sustained steal time means the underlying physical host is running more total vCPU (virtual CPU) demand than it has physical core capacity for at that moment. That can be entirely legitimate (the host is genuinely busy across all its tenants) or it can indicate a specific noisy-neighbor tenant burning disproportionate CPU. Either way, steal is fundamentally a signal about the HOST's oversubscription level, something the tenant cannot see or control directly, only feel the effect of.
How it manifests to the tenant
CPU-bound work inside the guest takes longer in wall-clock time than its actual CPU time would suggest, while the guest's own process-level CPU percentage looks unremarkable, because the guest kernel's scheduler only knows about the time it actually got to run, not the time it was ready but denied. This produces exactly the confusing pattern that trips up on-call engineers: latency spikes with no corresponding saturation visible in any guest-level dashboard, because the bottleneck lives one layer below what the guest can see.
How to detect it
toporvmstat 1, thestcolumn: a percentage of the sampling interval spent in steal state. A sustained value in the high single digits or above on a latency-sensitive workload (a rule of thumb, not a hard specification, since tolerance varies by SLA, Service Level Agreement, the promised performance target) is worth investigating./proc/stat, field 8 of the aggregatecpuline, exposes the same data as a cumulative counter, useful for building a time-series alert by computing the delta over each scrape interval.- Some cloud providers expose host-level or CPU-credit-style metrics outside the guest that can corroborate a steal reading from the provider's own side, where available.
How to mitigate it as an SRE
- Move to a less-oversubscribed instance family or size, or a dedicated/isolated-tenancy option where the provider offers one.
- In a fleet you control (private cloud, KVM), track host-level vCPU-to-physical-core ratio as a first-class fleet health metric, not just per-guest CPU percentage, and avoid bin-packing too aggressively.
- For latency-SLA-critical workloads, prefer CPU-pinned or dedicated-core instance types where available, which are explicitly not time-shared with other tenants.
- Treat steal as a first-class SLO (Service Level Objective, the internal target a team sets to stay within its SLA) input alongside guest CPU percentage, and where you control the hypervisor, correlate steal spikes with neighboring-tenant activity to identify and isolate the actual noisy neighbor.
- Scale out across more, smaller instances spread over more physical hosts, which reduces the blast radius any single host's contention has on the service's aggregate tail latency.
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.
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.