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 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 read-ahead and prefetching mechanisms at OS and application levels. When does read-ahead improve performance and when can it harm throughput or latency? Describe how you would tune readahead for a media streaming service serving large sequential reads.
Sample Answer
Direct answer
Read-ahead is the kernel (or an application) speculatively fetching data beyond what was explicitly requested, betting that a sequential access pattern will keep asking for the next chunk. It helps when access really is sequential and predictable, because it hides storage latency by having data ready before it's asked for. It hurts on random-access workloads, where it wastes I/O bandwidth and evicts genuinely useful cached pages fetching data that's never used. For a media streaming service serving large sequential reads, you'd deliberately increase the block-device readahead window well beyond the default.
Structured elaboration
OS-level read-ahead. The kernel detects a sequential access pattern to a file (successive reads at increasing offsets) and issues additional reads ahead of what the application asked for, populating the page cache before those blocks are requested. This is controlled per block device via the readahead setting, viewable and settable with blockdev --getra/--setra /dev/sdX (values are in 512-byte sectors), and persisted across reboots via a udev rule that reapplies the setting when the device is detected.
Application-level prefetching. Applications can give the kernel explicit hints rather than relying purely on heuristic detection: posix_fadvise(fd, ..., POSIX_FADV_SEQUENTIAL) tells the kernel to be more aggressive about read-ahead for this specific file descriptor, and POSIX_FADV_WILLNEED explicitly requests the kernel start prefetching a specific range immediately. Databases commonly do their own index-page prefetching above the OS layer, and media servers or download managers may issue explicit range-request prefetching over the network, a similar idea one layer up the stack.
When it helps. Any workload with a genuinely predictable, sequential access pattern: streaming a large media file, a full table scan, sequential log processing. The core mechanism is hiding storage latency by overlapping "fetch the next chunk" with "process the chunk you already have," so by the time the application asks for the next piece, it's already in cache.
When it hurts. Random-access workloads, most notably databases doing index lookups scattered across a large file, where the "next" blocks read-ahead fetches speculatively are usually never actually requested. This wastes I/O bandwidth on the storage device (competing with real requests) and pollutes the page cache by evicting genuinely hot pages to make room for speculative ones that go unused, hurting both throughput (wasted device bandwidth) and latency (real requests now queue behind speculative ones, and useful cache entries get evicted).
Tuning for a media streaming service. Increase the block device's readahead window well above the default (commonly 128 KB) to something sized for the streaming bitrate and access pattern, for example:
blockdev --setra 8192 /dev/nvme0n1
8192 sectors of 512 bytes each is 4 MB, a much larger anticipatory read window suited to sustaining large sequential streams at high bitrate with fewer, larger I/O operations rather than many small ones. Pairing this with an explicit posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL) call from the serving application lets the kernel be aggressive about read-ahead for that file from the very first read, rather than waiting for its own heuristics to detect the sequential pattern after a few reads have already happened. Because this trades page cache capacity for prefetch depth, validate against your actual cache hit ratio on a multi-tenant streaming box: a readahead window large enough to help one stream but big enough to evict other tenants' hot content is a net loss.
Worked example
Default readahead (blockdev --getra typically reporting 256 sectors, 128 KB) on a media server sustaining a 20 Mbps stream means the kernel issues many small anticipatory reads to keep up, each one a separate I/O operation with its own queueing and completion overhead. Increasing that to 8192 sectors (4 MB) means far fewer, larger I/O operations are needed to sustain the same stream, which reduces per-operation overhead and gives the kernel a much bigger buffer of already-fetched data to hide any transient storage latency behind. The trade-off becomes visible on a multi-tenant box: if 200 concurrent streams each get the configured 4 MB working set of read-ahead data cached (matching the 8192-sector/4 MB setting above), that's 200 x 4 MB = 0.8 GB of cache committed to prefetch alone, worth explicitly sizing against total available cache rather than assuming a larger number is free.
Trade-offs and pitfalls
Applying a large readahead window globally to a device that serves both sequential (streaming) and random (metadata lookups, small file serving) workloads is the most common mistake: the random-access traffic pays the read-ahead tax (wasted bandwidth, cache pollution) without getting any of the sequential-access benefit. If the same device serves mixed workloads, prefer per-file posix_fadvise hints from the application over a single global blockdev setting, so the tuning only applies to the traffic that actually benefits from it.
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 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.
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.
Unlock Full Question Bank
Get access to all 14 System Resource & I/O Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.