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 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 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.
Design a reproducible benchmark to compare disk throughput and latency across block sizes and queue depths using fio or similar tools. Specify exact test parameters (direct I/O flags, runtime, warmup, iodepth), metrics to capture, how to avoid page cache effects, and how to present results meaningfully.
Sample Answer
Direct answer
Use fio (Flexible I/O tester, the standard Linux disk-benchmarking tool) with direct=1 to bypass the page cache (the kernel's in-memory cache of recently read/written disk blocks, which would otherwise let a small working set serve reads from RAM and make the disk look far faster than it is), sweep a small matrix of block sizes and queue depths (iodepth), run each combination long enough to reach steady state after a discarded warmup period, and report IOPS (I/O operations per second), throughput, and latency percentiles (not just the average) for each cell. The result you present is not a single number but a table (or a latency-versus-throughput curve) showing where the device's latency starts climbing sharply as queue depth increases, which is the actionable signal for capacity planning.
Structured elaboration
Test matrix. Sweep two dimensions independently, holding the other fixed at a representative default, then run the full cross product if time allows:
- Block sizes: 4KiB, 16KiB, 64KiB, 256KiB, 1MiB (spans small-random-IO-dominated to large-sequential-dominated workloads).
- Queue depths (
iodepth): 1, 4, 8, 16, 32, 64 (spans "nothing in flight, latency-bound" to "deeply queued, throughput-bound"). - Access pattern: run
randread,randwrite,read(sequential), andwrite(sequential) as separate jobs; random and sequential performance can differ by an order of magnitude on the same device, especially spinning disks, and conflating them hides that.
Exact fio parameters, and why each one is there.
[job]
ioengine=libaio ; async I/O engine so iodepth actually queues multiple requests
direct=1 ; O_DIRECT: bypass the page cache, talk straight to the block device
rw=randread ; swept: randread, randwrite, read, write
bs=4k ; swept: 4k, 16k, 64k, 256k, 1m
iodepth=16 ; swept: 1, 4, 8, 16, 32, 64
numjobs=1 ; keep at 1 for a single-queue characterization; raise separately to test concurrency scaling
size=20g ; working-set size, chosen larger than the box's RAM (see cache note below)
runtime=60 ; steady-state measurement window
ramp_time=10 ; warmup, EXCLUDED from reported stats
time_based=1 ; keep running for the full runtime even if size is read/written before then
group_reporting=1 ; one aggregated report per job, not per-thread
invalidate=1 ; (fio default) drop cached pages for the target before the run starts
output-format=json ; machine-parseable, needed to pull clat percentiles programmatically
direct=1is the primary page-cache bypass; it forces every I/O throughO_DIRECT, which requires the buffer, offset, and length to be aligned to the device's logical block size (typically 512B or 4096B) or the I/O fails, which is why block sizes below 4KiB are usually skipped on modern devices.sizedeliberately larger than system RAM (or run against a raw block device with no filesystem at all, when that is safe to do) is a second, independent safeguard against page-cache effects: even withdirect=1, some filesystems and layers can still exhibit caching behavior for metadata or via a volume manager layer, so making the dataset not fit in RAM removes any ambiguity.ramp_time=10runs and discards 10 seconds before fio starts counting, so the numbers reflect steady-state device behavior, not the initial burst while queues are filling up from empty.- For a batch of these jobs run back to back in one job file (all block-size/iodepth combinations in sequence), add
stonewallbetween job stanzas so they run strictly one after another rather than fio trying to run them concurrently, which would make every cell's numbers reflect contention with its neighbors instead of the device alone.
Metrics to capture, per cell. IOPS, throughput (MB/s), and latency (clat, completion latency) at p50, p95, p99 (the 50th/95th/99th percentile, the value below which that percentage of requests complete; p99 is roughly the slowest 1%), and max, not just the mean: a device can have a fine average latency and a terrible p99 under load, and average-only reporting hides exactly the tail behavior most latency-sensitive services care about. fio's JSON output includes a clat_ns.percentile block when output-format=json and appropriate percentile_list is set (e.g. percentile_list=50:95:99:99.9).
Presenting results meaningfully. A flat table of (block size x queue depth) cells with IOPS/throughput/p99 is the raw data; the meaningful presentation on top of it is a latency-versus-achieved-throughput curve per block size, with queue depth as the swept parameter along the curve. As queue depth increases from 1 upward, throughput climbs roughly linearly at first while latency stays low and flat; past some point (the "knee"), additional queue depth buys little or no extra throughput while latency grows sharply, because the device is now saturated and requests are simply queueing. That knee, not the peak IOPS number alone, is the number worth reporting for capacity planning: it tells you the queue depth beyond which you are trading latency for no real throughput gain.
Worked example
Illustrative shape of the result, with plausible but non-measured numbers to show the pattern a real run would reveal, on a hypothetical NVMe device, random 4KiB reads:
| iodepth | IOPS | p50 latency | p99 latency |
|---|---|---|---|
| 1 | 9,500 | 0.10 ms | 0.25 ms |
| 4 | 34,000 | 0.11 ms | 0.35 ms |
| 16 | 110,000 | 0.14 ms | 0.60 ms |
| 32 | 145,000 | 0.21 ms | 1.40 ms |
| 64 | 152,000 | 0.40 ms | 4.80 ms |
Reading this: IOPS scales close to linearly with queue depth through iodepth 16, then flattens sharply between 32 and 64 while p99 latency roughly triples over the same range (1.40ms to 4.80ms, about a 3.4x increase). The knee sits around iodepth 32: that is the depth to design an application's connection pool or async I/O concurrency around, not 64, because past 32 the device gives back almost nothing in throughput while candidate requests wait far longer.
Trade-offs and pitfalls
- Testing against a file inside a filesystem (even with
direct=1) versus a raw block device can differ because of filesystem-level overhead (allocation, journaling, metadata updates on writes); state explicitly which one was tested, since the two are not interchangeable results. - Write tests are destructive and, on flash-based devices, contribute to wear; run write benchmarks against scratch/disposable devices or partitions, never against a device holding data you care about, and be aware that a fresh flash device can show artificially high write performance until it has been "conditioned" by prior writes (SSD steady-state behavior differs from a factory-fresh drive).
- A single short run can be misleading on devices with large internal caches (some SSDs/HBAs (HBA: host bus adapter, the controller card connecting the drive) have their own DRAM or SLC cache (a small, fast-but-expensive flash tier some SSDs use as a write buffer) ahead of the slower backing media): a short
runtimecan measure the cache's speed, not the device's sustained speed. Extendruntime(minutes, not seconds) when characterizing sustained rather than burst performance. numjobs=1deliberately isolates single-queue behavior from application-level concurrency; if the real workload issues I/O from many threads/processes concurrently, also run anumjobssweep, since aggregate throughput and per-request latency under many concurrent issuers do not simply multiply from the single-job numbers.- Comparing results across different runs or machines only makes sense if every parameter that affects the outcome (block size, iodepth, engine, direct flag, runtime, filesystem vs raw device) is held identical and stated alongside the numbers; a throughput number with no stated block size or queue depth is not a meaningful benchmark result.
Design and implement a fixed-size buffer strategy for reading lines from a very large file where lines can be longer than the buffer. The API should read the file in chunks and return complete lines to the caller without loading the entire file into memory. Describe how you handle partial lines, multi-byte encodings, and performance trade-offs.
Sample Answer
Approach
Read fixed-size byte chunks from the file, accumulate them in a small internal buffer, split on newline bytes, hand back every complete line found, and carry the trailing partial fragment forward into the next read, growing it across as many chunk reads as it takes for a single line to complete. Decode text only once a line is known to be complete (bounded by a newline or end of file), which is what keeps multi-byte characters from being corrupted by a chunk boundary landing in the middle of one.
Implementation (Python)
def read_lines(path, bufsize=8192):
"""Yield complete text lines from `path`, reading at most `bufsize`
bytes at a time, without ever holding more than one buffered chunk
plus one pending (possibly very long) line in memory.
Lines may be longer than bufsize: a partial line is carried over and
grown across as many chunk reads as it takes until a newline turns
up. Multi-byte UTF-8 sequences are never decoded until they are
known to be complete, so a chunk boundary landing mid-character does
not corrupt the text or raise a spurious UnicodeDecodeError.
"""
pending = b""
with open(path, "rb") as f:
while True:
chunk = f.read(bufsize)
if not chunk:
break
pending += chunk
lines = pending.split(b"\n")
pending = lines.pop() # last element: partial line, or b"" if
# the chunk happened to end on a newline
for raw_line in lines:
yield raw_line.decode("utf-8")
if pending:
yield pending.decode("utf-8")
Output
Tested with bufsize=8, deliberately smaller than every line in the file, including one containing accented and CJK (Chinese/Japanese/Korean multi-byte) characters, against a file containing a short line, a 50-character line (far longer than the 8-byte buffer), a multi-byte-heavy line, and a final line with no trailing newline:
0: 'short'
1: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
2: 'café éééé 中文文文 done'
3: 'last-no-newline'
OK: matches str.split('\n') on the original content
Every line, including the multi-byte one, came back byte-for-byte correct despite the 8-byte read buffer splitting mid-character on nearly every read, and the result matched a plain in-memory str.split("\n") on the original content exactly.
Key points
Partial lines: the pending buffer holds only unterminated bytes; bytes.split(b"\n") gives back every complete segment plus the trailing (possibly empty) remainder in one call, so there is never a separate "did I finish a line" check to get wrong. A line longer than bufsize simply causes pending to keep growing across multiple read() calls until a newline finally appears in some later chunk, the loop does not need special-casing for that case, it falls out of the same logic. Multi-byte encodings: decoding happens only on raw_line, a byte string already known to be bounded by a real newline or true end of file, so any UTF-8 multi-byte sequence inside it is always complete by construction; decoding the raw chunk bytes directly (before splitting) would risk cutting a multi-byte character in half and raising UnicodeDecodeError, or worse, silently producing wrong characters with a more permissive decode mode.
Performance trade-offs
bufsize trades memory against system-call overhead: a small buffer (a few hundred bytes) keeps peak memory tiny but issues many more read() system calls for a large file, each with its own kernel-transition cost; a large buffer (64KB-1MB) amortizes that cost across more data per call at the price of higher peak memory, though still bounded and predictable, unlike loading the whole file. pending += chunk reallocates and copies the accumulated buffer on every chunk for files with unusually long lines; for a workload expected to have many very long lines, a bytearray with in-place extend() avoids the repeated string-concatenation copy that plain bytes concatenation incurs. This implementation also does not require the file to fit any particular line-length assumption up front, unlike a strategy that pre-allocates a fixed-size line buffer and errors on overflow, at the cost of no longer having a hard upper bound on how much memory one single pathologically long line can consume.
Edge cases
An empty file yields no lines. A file with no trailing newline still yields its final line correctly (the if pending: check after the read loop ends). A file consisting of only newlines yields a sequence of empty-string lines, which matches str.split("\n") semantics exactly, verified in the test above. A bufsize of 1 would still be correct, just extremely slow, since the logic makes no assumption about how much of a line arrives per chunk.
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.
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.