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.
Live-coding scenario: You receive a working function that processes an entire input file into memory. The interviewer asks you to adapt it to process arbitrarily large files using streaming/chunked processing without changing the public API. Describe and implement the core change in Python (pseudocode acceptable) and list tests you'd add.
Sample Answer
Approach
The public API is the function's signature and its return type/value, not its internal implementation, so the retrofit only has to change how the function reads its input, from one read() call that materializes the whole file, to iterating the file object line by line, which Python's own file objects already do with a small internal read-ahead buffer rather than loading everything at once. Nothing about the call site, the arguments, or what the function returns needs to change.
Before and after (Python)
# BEFORE: loads the whole file into memory
def word_frequencies(path):
with open(path, "r", encoding="utf-8") as f:
text = f.read() # whole file materialized here
freq = {}
for word in text.split():
freq[word] = freq.get(word, 0) + 1
return freq
# AFTER: identical signature, identical return type, streams the input
def word_frequencies(path):
freq = {}
with open(path, "r", encoding="utf-8") as f:
for line in f: # file objects iterate line-by-line
for word in line.split(): # under the hood via a small internal
freq[word] = freq.get(word, 0) + 1 # buffer, never the whole file
return freq
Output
Ran both versions against the same 200,000-line generated file and compared results directly, rather than assuming the rewrite was equivalent:
public API unchanged: both return dict -> True
results identical: True
sample counts (word0, token0): 4000 28572
Both counts were hand-checked against the generation pattern (word{i % 50} and token{i % 7} for i in range(200_000)): word0 should appear once per 50 lines, 200000 / 50 = 4000, and token0 once per 7 lines starting at i=0, which is 28572 occurrences (i values 0, 7, 14, ..., 199997, that's 199997/7 + 1 = 28572 values), both matching the printed output exactly.
Key points
The only structural change is swapping f.read() (returns the entire file as one string) for iterating f directly (returns one line at a time, advancing an internal, bounded read buffer as it goes); Python guarantees file objects are iterable line-by-line without any extra library. Peak memory now scales with the longest single line and the size of the freq dictionary (the output), not with the size of the input file, which is exactly the goal, since the output of a word-frequency count is normally far smaller than the input text regardless. No caller-visible behavior changed: same function name, same parameter, same return type, so anything already calling word_frequencies(path) needs no changes at all.
Tests to add
An empty file, expect an empty {} result rather than an error. A single line with no trailing newline, the common off-by-one case for line-based readers, to confirm the last line is not silently dropped. A file where one line is far longer than a typical chunk/buffer size, to confirm no artificial line-length limit was accidentally introduced. A file with non-ASCII/multi-byte UTF-8 text, to confirm the encoding argument is still honored identically to the original. A large synthetic file (as used above) run through both the old and new implementation with results compared for exact equality, this is the test that actually proves the retrofit preserved behavior, rather than just looking correct by inspection. A memory-usage assertion (peak RSS, resident set size, sampled during execution) run only against the new version on a large file, to prove memory no longer scales with file size, which is the entire point of the change and the one property a pure output-equality test cannot verify on its own.
Trade-offs and pitfalls
This retrofit works cleanly because the original function's output (a frequency count) does not require the whole input to be resident at once, word counting is naturally streamable. Not every full-load-to-streaming retrofit is this clean: a function that needs random access into the file (seeking backward, or needing the total line count before processing the first line) cannot simply switch to line-by-line iteration without a real design change, sometimes a second pass, sometimes a different algorithm entirely. The other common trap in a live-coding version of this task is changing the return type along the way (for instance, switching to a generator that yields incrementally) to look more "streaming"; that would actually break the public API the question explicitly says not to change, since callers expecting a dict back would get a generator object instead.
What is the Linux page cache, and how does the kernel use it to speed up reads and writes? Explain buffered writes and write-back behavior, what fsync actually guarantees, and how you'd tell whether a workload is genuinely benefiting from the page cache versus just accumulating memory pressure that you should reclaim.
Sample Answer
Direct answer
The page cache is RAM the kernel uses to hold copies of disk blocks so repeat reads are served from memory instead of storage, and so writes can return quickly while the kernel flushes them to disk in the background. A write() call normally just copies data into the page cache and marks those pages dirty; it does not wait for the disk. fsync() is the call that forces those dirty pages (and, unlike fdatasync(), the file's metadata) to actually reach the storage device before it returns. Whether the page cache is helping or just eating memory comes down to one field: MemAvailable, not MemFree.
Structured elaboration
Buffered writes and write-back. By default, file I/O in Linux is buffered: write() copies your data into page-cache pages and returns immediately. Those pages are marked "dirty" (modified but not yet on disk). Kernel writeback threads (one per backing device) flush dirty pages to disk asynchronously, governed by two sysctls: vm.dirty_background_ratio (the percentage at which background flushing starts quietly) and vm.dirty_ratio (the percentage at which the writing process itself gets blocked until writeback catches up). Both percentages are taken against dirtyable memory, meaning free plus reclaimable pages, not against total RAM, so the byte ceiling they imply shrinks as anonymous memory grows; vm.dirty_bytes/vm.dirty_background_bytes set the same thresholds as absolute byte counts when you need a fixed bound. This is why a burst of writes can feel instant at first and then suddenly stall: you've crossed dirty_ratio and the kernel is now throttling you.
What fsync actually guarantees. fsync(fd) flushes all dirty pages belonging to that file descriptor to the underlying block device, and issues a cache-flush/FUA (force unit access) command so the write is committed past any volatile cache on the device itself, not just handed to the disk controller. Once fsync() returns successfully, that data survives a kernel crash or power loss, assuming the device honors flush commands correctly (a device with a broken or disabled write-cache flush can lie about this, which is a real failure mode to check for, not a theoretical one). fdatasync() gives the same data guarantee but skips flushing metadata that isn't needed to read the data back (e.g. mtime), which is cheaper when you don't need it.
Where O_DIRECT fits. O_DIRECT is an open flag that bypasses the page cache entirely for that file, transferring data close to directly between your buffer and the device. It exists for applications, mostly databases, that manage their own buffer pool and don't want the OS silently double-caching (and double-copying) the same pages. The trade-off: you give up the free page cache readahead and write coalescing the kernel would otherwise do, and you take on the responsibility for your own caching and I/O scheduling. O_DIRECT alone still does not guarantee durability: you generally still need fsync or O_DSYNC (an open flag that folds an fdatasync-equivalent durability guarantee into every write() call, syncing the data plus only the metadata needed to read it back; O_SYNC is the stronger sibling that folds in a full fsync-equivalent guarantee, including metadata like mtime that isn't needed to retrieve the data), because the storage device can have its own volatile write cache sitting below O_DIRECT.
Genuine benefit versus memory pressure. Don't judge this from free memory alone; idle RAM used for cache is not a problem by design. Instead:
- Check
MemAvailablein/proc/meminfo(or theavailablecolumn offree -h). This is the kernel's own estimate of how much memory could be freed for new allocations without swapping, after accounting for reclaimable cache. HighMemAvailablerelative to total RAM means the cache is healthy and reclaimable on demand. - Check
DirtyandWritebackin/proc/meminfo. IfDirtyis climbing toward yourdirty_ratiothreshold, you're accumulating unflushed writes, not free performance. - Watch
vmstat 1forsi/so(swap in/out). Any sustained non-zero value means real pressure is forcing anonymous memory to disk, which is a different and much worse problem than "a lot of cache." - Look at
/proc/pressure/memory(pressure stall information, a kernel-reported metric of how much time processes actually stalled waiting on memory). Near-zeroavg10means processes aren't stalling; rising values mean the cache size is a symptom of real contention, not a free lunch.
Worked example
On a 64 GB box that's been serving reads for a while, free -h might show:
total used free shared buff/cache available
Mem: 62Gi 11Gi 1.2Gi 450Mi 49Gi 48Gi
Swap: 0B 0B 0B
49 GiB is sitting in buff/cache, but available is 48 GiB, almost the same. That tells you the kernel considers nearly all of that cache reclaimable right now: it's genuinely free capacity being used productively, not memory the system is straining to hold onto. Contrast that with a box where available has dropped to 4 GiB despite 49 GiB of buff/cache: that gap means most of that "cache" is actually dirty pages waiting on writeback, or the kernel is close to needing to reclaim aggressively, which is your early warning to check Dirty in /proc/meminfo and vmstat's si/so before it turns into swapping or an OOM (out-of-memory) kill, where the kernel terminates a process to free memory it can't reclaim any other way.
Trade-offs and pitfalls
The most common mistake is alerting on low MemFree directly, which pages nearly every healthy Linux box in existence, since the kernel is designed to use spare RAM for cache rather than leave it idle. Alert on MemAvailable instead. The second common mistake is assuming fsync guarantees durability against every failure mode: a storage controller with a volatile write cache that ignores flush commands, or a filesystem mounted with barriers disabled, can make fsync return success while data is still one power outage away from being lost. On database servers this is worth verifying explicitly rather than assuming the defaults are safe.
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.
Explain NUMA (Non-Uniform Memory Access) and its effects on performance in multi-socket servers. How would you design and tune a service to be NUMA-friendly including CPU/memory pinning, thread affinity, allocator choices, and testing approaches?
Sample Answer
Design principle: shared-nothing per node, not one big shared heap
NUMA (Non-Uniform Memory Access, where each CPU socket has its own local memory and reaching another socket's memory costs extra latency over an inter-socket interconnect) rewards a design that partitions work by node rather than one that lets any thread touch any memory freely. The strongest NUMA-friendly pattern is to shard the service's data and threads one partition per node, so each node's threads mostly touch that node's own memory by construction, instead of trying to retrofit locality onto a shared-everything design after the fact.
Thread and CPU affinity
Pin worker threads to the CPUs of a single node at startup, using pthread_setaffinity_np() in C/C++ or an equivalent affinity API in the runtime, or by launching the process under numactl --physcpubind. Without pinning, the OS scheduler can migrate a thread to a core on a different node mid-run; each such migration risks a burst of remote memory accesses until the thread's working set effectively 'catches up' by being re-touched (and thus reallocated) on the new node.
Allocator choice
- Use a NUMA-aware allocator, for example jemalloc or tcmalloc configured with one arena per node (or per thread, matched to node count), so allocations naturally land on the calling thread's local node instead of a single global arena that anyone can touch.
- Linux uses a first-touch allocation policy for anonymous memory: a page is not actually assigned to a physical NUMA node until the first time something writes to it, regardless of which node's allocator called
malloc(). For large, latency-sensitive structures, allocate explicitly withnuma_alloc_onnode()ormbind()and make sure the FIRST touch genuinely happens on the intended node, since a naive 'warm-up' loop run on the wrong thread can silently place memory on the wrong node before the real workload ever runs.
Testing approach
- Before investing in NUMA-aware code, measure whether the penalty is real on this specific workload and hardware: run the same benchmark under
numactl --membindforced to the local node versus forced to a remote node, and compare. The gap varies a lot by platform and workload, so guessing is a bad use of engineering time; an A/B measurement settles it. - During a real load test, check
numastatdeltas per process to confirm the design's INTENDED locality is what actually happens at runtime, since fragmentation or an allocator falling back under pressure can quietly break locality even when the code was written correctly.
Explain and demonstrate with pseudocode how to use sendfile or a zero-copy transfer to serve static files on Linux over TCP to reduce CPU copies. Discuss limitations such as file descriptors, inability to use sendfile with TLS in some stacks, and when splice or kTLS are alternatives.
Sample Answer
Approach
Serving a static file the ordinary way (read() into a userspace buffer, then write() to the socket) costs two data copies (disk cache to userspace buffer, userspace buffer to socket buffer) and at least two user/kernel context switches. sendfile() asks the kernel to copy the file's page-cache pages straight into the socket's send buffer without ever handing the bytes to userspace, cutting the copy count and the syscall count.
Demonstration (real, executed)
The following Python code uses os.sendfile(), the direct syscall wrapper, to serve a file over a loopback TCP socket. It was run as written; the printed output below is the actual result of that run, not a hypothetical.
import os, socket, threading, tempfile
data = b"X" * (64 * 1024) # a 64 KiB "static file"
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(data)
fname = f.name
def server(holder):
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 0))
srv.listen(1)
holder["port"] = srv.getsockname()[1]
holder["ready"].set()
conn, _ = srv.accept()
with open(fname, "rb") as fh:
filesize = os.fstat(fh.fileno()).st_size
offset, sent_total = 0, 0
while sent_total < filesize:
sent = os.sendfile(conn.fileno(), fh.fileno(), offset, filesize - sent_total)
if sent == 0:
break
offset += sent
sent_total += sent
conn.close(); srv.close()
holder["sent"] = sent_total
holder = {"ready": threading.Event()}
t = threading.Thread(target=server, args=(holder,)); t.start()
holder["ready"].wait()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", holder["port"]))
received = b""
while len(received) < len(data):
chunk = client.recv(65536)
if not chunk:
break
received += chunk
client.close(); t.join()
print("bytes sent via os.sendfile():", holder["sent"])
print("bytes received by client:", len(received))
print("payload matches:", received == data)
os.unlink(fname)
Output:
bytes sent via os.sendfile(): 65536
bytes received by client: 65536
payload matches: True
os.sendfile(out_fd, in_fd, offset, count) mirrors the Linux syscall signature exactly: it copies count bytes from in_fd (a regular file, must be mmap-able) to out_fd starting at offset, and returns how many bytes it actually moved so the loop above can resume on a short transfer. out_fd has always been allowed to be a socket, which is the case this demo uses; the version boundary actually runs the other way. Before Linux 2.6.33, out_fd was required to be a socket; since 2.6.33 it can be any file, including a regular file, which is what additionally enables file-to-file zero-copy transfers, not the socket case this demo already relied on.
Key points
in_fdmust be a regular file (or a file the kernel can page-cache), not a pipe or arbitrary character device: the kernel is copying page-cache pages, not streaming arbitrary bytes.- On modern NICs, the copy can be a scatter-gather DMA (Direct Memory Access: hardware moves the data without the CPU copying it byte by byte) straight from page cache to the NIC, so there may be zero CPU-driven copies at all, only DMA.
Limitations
- File descriptor limits:
sendfile()needs valid, seekable file descriptors on both ends; it cannot serve from a socket-to-socket relay directly. - TLS:
sendfile()hands raw file bytes to the kernel network stack. TLS encryption normally happens in userspace (OpenSSL, etc.), which requires touching the plaintext, defeating the zero-copy path entirely, so a plain TLS-terminating server usually cannot usesendfile()for the encrypted response body. - kTLS (kernel TLS) is the fix: once the TLS session keys are handed to the kernel, the kernel encrypts the data during the same copy
sendfile()already does, restoring the zero-copy path for encrypted traffic. splice()is the more general alternative: it moves data between two file descriptors via an intermediate kernel pipe buffer, so it also covers socket-to-socket proxying, a case plainsendfile()does not handle well.
Unlock Full Question Bank
Get access to all 8 System Resource & I/O Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.