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.
Hard: You're debugging severe tail latency in a distributed storage daemon. Perf shows many samples in kernel function 'ext4_file_write_iter' and io latency metrics show long await times on multiple devices. Propose a plan to narrow down whether the problem is device-level (underlying disks), kernel-level (filesystem), or workload-level (filesystem usage pattern). Suggest experiments and mitigations.
Sample Answer
Framing
Two signals are given together: perf shows heavy CPU time inside the kernel function ext4_file_write_iter (the ext4 filesystem's write entry point), and iostat's await (average time an I/O request waits, including queueing, before completing) is long on MULTIPLE devices at once. The multi-device pattern is the key clue: it argues against a single failing disk and toward something shared across devices, either the filesystem/kernel layer or the workload pattern hitting every device the same way.
Device-level hypothesis
Run iostat -xz 1 per device. %util near 100 percent with high await and a reasonable service time (efficient use of that busy time) means the device itself is genuinely saturated, a real hardware limit. %util only moderate but await still high, alongside a high avgqu-sz (average queue depth), means requests are piling up somewhere BEFORE they reach the device efficiently, pointing away from the device itself and toward the I/O scheduler or filesystem layer above it.
Kernel/filesystem-level hypothesis
Heavy time actually spent executing inside ext4_file_write_iter (CPU time, not just iowait/D-state blocking) suggests the write path's own code is the bottleneck, not just waiting on hardware. A common cause is journal (jbd2, ext4's journaling block device thread) contention: under data=ordered or data=journal mode with many small or fsync-heavy writes hitting the same filesystem, journal commits can serialize writes across unrelated files sharing that filesystem. Checking jbd2/<dev>-8 kernel thread CPU usage, or inspecting /proc/<jbd2_pid>/stack, shows whether the journal thread itself is the bottleneck. Multiple devices showing the same hot kernel function simultaneously strongly favors a shared kernel/filesystem-level resource, such as journal locking or global writeback throttling (vm.dirty_ratio), over N independently failing disks.
Workload-level hypothesis
Check the actual write pattern: size distribution and fsync frequency, either from application metrics or logs. Many small writes (well under 4 KiB) each followed by an fsync is a classic pathological pattern that amplifies journal commit overhead and defeats writeback coalescing (the kernel's normal batching of dirty pages before flushing to disk). Reproducing the daemon's exact write pattern with fio (a flexible I/O benchmarking tool) against a spare device of the same type isolates whether the SHAPE of the workload, not the device or filesystem in the abstract, is driving the latency.
Experiments, cheapest and safest first
- Correlate
iostat -xzandperf top -gin time with the daemon's own latency metric during a live incident window, no changes made yet, just correlation. - Replay the daemon's actual write pattern with
fioagainst an idle spare device of the same type, reproducing the problem in isolation without touching production. - Canary a mount-option change (
data=writebackif the application's own durability logic does not require ordered mode, or a separate journal device) on one host and compareawaitand tail latency against control hosts. - If the device genuinely is the bottleneck, quantify the cost/benefit of more devices or a faster tier rather than assuming a hardware upgrade is the answer by default.
Mitigations by which layer wins
If device-bound: spread the write-ahead log across more devices, or reduce fsync frequency at the application layer through group commit (batching several commits into one fsync). If filesystem/kernel-bound: change journal mode, move the journal to a separate device, or reconsider filesystem choice for this specific concurrent-small-write pattern. If workload-bound: batch small writes and increase the buffer before each fsync, reducing fsync-per-operation frequency in the daemon itself.
Explain the difference between a buffer and a cache in the context of I/O and memory. Include concrete examples where each is used (socket buffers, OS page cache, application-level caches), describe how they affect latency and throughput, and when you'd prefer one over the other in a backend service.
Sample Answer
Direct answer
A buffer temporarily holds data in transit between two things operating at different speeds, and once that data is consumed it's typically gone; it exists to smooth throughput and absorb bursts. A cache holds a copy of data specifically so it can be reused later, trading memory for avoiding a repeated expensive operation; it exists to cut latency and reduce load on whatever it's standing in front of. In a backend service you generally need both, sized for their different jobs, rather than choosing one over the other.
Structured elaboration
Buffers, and what they're for. A socket buffer (configured via SO_RCVBUF/SO_SNDBUF) holds bytes that have arrived from the network before the application reads them, or bytes the application has written before the kernel has finished sending them. It decouples the producer's rate from the consumer's rate, letting each side proceed at its own pace within the buffer's capacity. The data isn't kept for later reuse; once consumed, it's gone. Effect on throughput and latency: a buffer that's too small causes stalls or drops under bursts (the sender must wait or the packet is lost); a buffer that's too large causes "bufferbloat" (data sits queued for a long time before being processed, adding latency even though nothing is technically being dropped).
Caches, and what they're for. The OS page cache (kernel-managed, holds recently accessed disk blocks) and application-level caches (an in-process LRU, least-recently-used, cache in front of a database, or an external cache like Redis) both exist to serve a repeat request faster than redoing the original work, and secondarily to reduce load on the backing system, fewer disk reads, fewer database queries, which indirectly helps everyone else sharing that backend. Unlike a buffer, the data is deliberately kept around for reuse, governed by an eviction policy (commonly LRU) or a TTL (time-to-live, an expiry after which an entry is considered stale and discarded).
How each affects latency and throughput, side by side. A buffer's main effect is on throughput smoothness and burst tolerance: sized correctly, it prevents drops and stalls from rate mismatches; sized wrong in either direction, it either drops data or adds unnecessary queuing delay. A cache's main effect is on latency for repeat access: a cache hit skips the original expensive operation entirely, and its secondary effect is throughput for the whole system, since offloading repeat requests from the backend frees capacity for everyone else's requests too.
When to prefer one over the other in a backend service. In practice you don't choose between them, you apply each to the problem it actually solves. Size buffers (socket buffers, request queues) to absorb realistic burst and jitter without excessive queuing delay, neither so small that normal bursts cause drops nor so large that queued data sits stale by the time it's processed. Add a cache specifically for data that's read far more often than it changes, where some staleness within your TTL window is acceptable. A common design mistake is using a cache where you actually need a buffer, for example trying to "cache" write-once event data that should really just be queued and drained, or the reverse, failing to add a cache in front of a backend that genuinely can't sustain the real read rate without one.
Worked example
A backend service accepting webhook events over a socket needs an appropriately sized SO_RCVBUF (a buffer) so a burst of simultaneously arriving events doesn't get dropped by the kernel before the application has a chance to read them; that data is processed once and discarded, no reuse involved. The same service, when it needs to look up a customer's plan tier to decide how to route each event, benefits from an application-level cache (an in-process map or an external cache like Redis) in front of the database, since the same customer's plan tier is looked up repeatedly across many events and rarely changes, making it a textbook case for reuse-oriented caching with a short TTL (a few minutes is often enough to keep the data reasonably fresh while eliminating the vast majority of repeat database lookups).
Trade-offs and pitfalls
Oversizing a buffer to "be safe" is a common mistake with a real cost: it doesn't prevent drops any better once the true burst exceeds even the larger buffer, but it does add latency to everything that queues behind a large backlog (bufferbloat), which can make a service feel sluggish under load even though nothing is technically failing. On the cache side, the common mistake is caching data that changes on every access (defeating any reuse benefit while adding cache-management overhead for nothing) or setting a TTL so long that stale data causes real correctness problems downstream.
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: You find a process consuming large amounts of file descriptors and causing EMFILE errors globally. Propose a plan to debug where descriptors are coming from, short-term mitigations to restore service, and long-term design changes to prevent descriptor leaks. Include commands to gather evidence.
Sample Answer
Direct answer
Start by counting and categorizing which file descriptors a suspect process is actually holding, using /proc/<pid>/fd and lsof, to find out whether it's leaking sockets, regular files, or pipes. Mitigate immediately by raising that process's file descriptor limit without a restart (prlimit) and, if the global system table is also near its ceiling, raising fs.file-max. Fix the leak permanently by finding the code path that skips closing a handle, usually on an error branch, and add fd-count monitoring so the next leak pages someone before it becomes an outage.
Structured elaboration
Gathering evidence.
ls -la /proc/<pid>/fd | wc -lgives a quick count of currently open descriptors for the suspect process; sample this every few seconds in a loop to see if it's actively growing (a real leak) or just high but stable (a legitimately fd-heavy but healthy process).cat /proc/<pid>/limits | grep "Max open files"shows the soft and hard ulimit that process is bound by, so you know how much headroom is left before EMFILE (a per-process "too many open files" error) hits.lsof -p <pid>gives a human-readable listing with the type of each descriptor (regular file, socket, pipe, directory) and, for files, the actual path. This is where you find out what class of resource is leaking.- For sockets specifically,
ss -tnp state close-waitlists sockets stuck in theCLOSE_WAITTCP state, meaning the remote peer closed the connection but the application never calledclose()on its end. A pile of these is the single most common EMFILE root cause in networked services: a connection-handling code path that isn't releasing sockets on some error or timeout branch. - System-wide,
lsof | awk '{print $2}' | sort | uniq -c | sort -rn | headranks every PID by descriptor count, useful when you don't yet know which process is the culprit, andcat /proc/sys/fs/file-nrshows the system-wide allocated/free/max descriptor counts (fs.file-max), which tells you whether this is a single-process EMFILE or you're also close to the global ceiling.
Short-term mitigations, in rough order of speed.
- Raise the process's own limit live, without a restart:
prlimit --pid <pid> --nofile=<new-soft>:<new-hard>. This buys immediate headroom for the running process. - If the global table (
fs.file-nr's first field approaching its third field,fs.file-max) is also close to exhausted, raisefs.file-maxviasysctl -w fs.file-max=<new-value>. - Roll a staggered restart of the affected service's instances behind the load balancer to reset fd counts on each one while the underlying fix ships, spreading the restarts to avoid a thundering herd of reconnects hitting downstream dependencies at once.
- If you can identify the specific endpoint or client driving the leak, apply targeted rate limiting or backpressure there as a stopgap while a code fix is prepared.
Long-term fix. The root cause is almost always a code path, frequently an exception or error-handling branch, that returns or throws before a close() (or the language's equivalent, a try-with-resources block, a context manager, or a defer/finally cleanup) runs. Fix the leak at the source, then add regression protection: instrument fd count as a metric with alerting thresholds well below the ulimit (so you get paged before the next EMFILE, not after), and add a soak test that asserts the descriptor count is stable under sustained load rather than monotonically climbing. If the workload naturally opens and closes many connections, consider a connection pool with an idle timeout instead of ad hoc open/close per request, since pooling bounds the working set explicitly rather than relying on every code path remembering to clean up.
Worked example
Sampling ls /proc/12345/fd | wc -l every 10 seconds shows 4,200, then 4,850, then 5,600, a clear upward trend rather than a stable high number. lsof -p 12345 | awk '{print $5}' | sort | uniq -c shows the overwhelming majority are type sock. ss -tnp state close-wait | grep 12345 | wc -l returns a similarly large number, confirming the pattern: sockets where the remote side closed the connection but the process's own close() never fired, almost certainly a connection-handling error path that isn't cleaning up. That combination (growing fd count, dominated by sockets, dominated by CLOSE_WAIT) is specific enough to hand directly to the team owning that code as "your connection cleanup on the error path is leaking sockets," rather than a vague "check your file handles" report.
Trade-offs and pitfalls
Raising fs.file-max or a process's ulimit treats the symptom, not the leak; without also finding and fixing the code path, the same failure recurs on a longer timer with a higher ceiling. Restarting affected instances resets the count but loses any in-flight connections on those instances, so stagger it rather than restarting everything at once, especially behind a load balancer where a synchronized restart of every backend can itself cause a brief capacity dip.
Medium: A service under systemd sometimes fails to bind to a TCP port on startup with 'Address already in use' only when restarted quickly. How would you change the unit file and application to reduce the likelihood of this race? Explain TIME_WAIT implications and a system-level mitigation.
Sample Answer
Root cause: TIME_WAIT, not a systemd bug
After a TCP connection closes, the side that closed first holds that connection's 4-tuple (local IP/port, remote IP/port) in TIME_WAIT for 2*MSL (Maximum Segment Lifetime, roughly 60 seconds total on Linux by default) to guarantee any duplicate or delayed packets from the old connection cannot be mistaken for a new one. If the LISTENING socket itself was bound without SO_REUSEADDR, a fast restart can hit 'Address already in use' because the kernel refuses to bind a new listening socket to a port that still has any sockets, including TIME_WAIT ones, associated with it.
Application-level fix
Set SO_REUSEADDR on the listening socket before calling bind(). Most mature server frameworks already do this by default; a hand-rolled or minimal server might not, and that omission is the actual bug here, not TCP itself.
Unit file changes
- Add
RestartSec=<a few seconds>toRestart=on-failureas a crude mitigation: it gives the old socket time to fully release before the new process tries to bind. - The real system-level mitigation is socket activation: pair the service with a
.socketunit. systemd itself creates and binds the listening socket once, then hands it to the service process over a file descriptor on every restart. The listening socket now outlives individual restarts of the service entirely, so the bind race disappears rather than being merely reduced. - Ensure the unit has a real graceful shutdown path (a correct
ExecStopor signal handling that lets the process close its socket cleanly) rather than being SIGKILLed, since an abrupt kill can leave lingering state that makes the race more likely, not less.
TIME_WAIT implications to know
- TIME_WAIT is a correctness mechanism, not a bug to be tuned away in general. It prevents old duplicate segments from corrupting a new connection reusing the same address/port pair.
net.ipv4.tcp_tw_reuse=1is commonly confused with a fix for this: it allows outbound (client-side) connections to reuse a TIME_WAIT 4-tuple faster, but it has no effect on the ability to rebind a LISTENING socket, which is governed only bySO_REUSEADDR. Reaching fortcp_tw_reusehere is a common wrong turn worth explicitly ruling out in the answer.
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.