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 disk metrics: IOPS, throughput (MB/s), average latency, and queue depth. For a database workload consisting of many small random reads, which metrics matter most and how would you size storage (IOPS, latency targets, RAID considerations)?
Sample Answer
Direct answer
For a database doing many small random reads, latency and IOPS (input/output operations per second) are what matter most, not raw throughput; a storage tier can have huge MB/s on paper and still be a poor fit if each individual small read takes too long or the device cannot sustain enough operations per second at that block size.
The four metrics
IOPS counts distinct I/O operations completed per second, independent of how large each one is; it is the dominant metric for workloads dominated by many small, random operations. Throughput (MB/s) measures bytes moved per second and dominates for large, sequential transfers (backups, media streaming, bulk data loads) where a handful of large operations move most of the data. Average latency is the mean time from issuing an I/O request to its completion, including any queueing delay; it is what an application actually experiences per operation. Queue depth is the number of I/O requests outstanding (issued but not yet completed) at a given moment; a device can sustain higher aggregate throughput and IOPS at higher queue depths because it can reorder and batch requests, but each individual request's latency rises as the queue grows, since it has to wait behind others.
Which metrics matter most for many small random reads
IOPS and latency dominate. Throughput is close to irrelevant here: a database doing 8KB random reads scattered across a large table is bound by how many discrete operations the storage can service per second and how quickly each one completes, not by how many megabytes per second it can move in aggregate, since each operation only moves a small amount of data anyway. Queue depth matters as a secondary lever: a database connection pool issuing many concurrent reads can push queue depth up to extract more aggregate IOPS from the device, but past a certain point this trades away per-request latency (queueing delay grows) for aggregate throughput, which is the wrong trade for a latency-sensitive workload like an online transaction.
Sizing storage
Size for IOPS at the target block size first: get the actual block size the database reads at (Postgres and MySQL InnoDB commonly use 8-16KB pages) and size storage to the required IOPS at that block size specifically, since a device's IOPS rating at 4KB does not translate directly to its IOPS at 16KB (larger blocks reduce achievable IOPS at a given throughput ceiling). Set an explicit latency target (e.g. p99, 99th percentile, read latency under 5ms for an interactive OLTP workload, online transaction processing, transactional database work characterized by many small concurrent reads/writes rather than large batch scans) and validate against it with a synthetic benchmark (fio, Flexible I/O Tester, a standard Linux disk-benchmarking tool, with --rw setting the access pattern, --bs the block size, and --iodepth how many I/Os are issued concurrently, e.g. --rw=randread --bs=8k --iodepth=<N> matching the real connection pool's concurrency) rather than trusting a device's advertised peak numbers, which are usually measured at a much higher queue depth or larger block size than the real workload uses. For RAID (redundant array of independent disks, a way of combining multiple physical disks into one logical volume), RAID 10 (mirrored pairs, striped) is the standard choice for a random-read-and-write OLTP workload: it gives good random I/O performance and full redundancy without the write-amplification penalty RAID 5/6 incur from parity calculation on every write, at the cost of using half the raw capacity for redundancy. RAID 5/6 are a better fit for large, mostly-sequential, less write-latency-sensitive workloads (archival, backups) where their capacity efficiency matters more than random-write latency.
Trade-offs and pitfalls
Throughput numbers on a spec sheet are the easiest to market and the least relevant to this workload; do not size storage for a database off a throughput figure alone. Higher queue depth increases achievable aggregate IOPS but at the cost of per-request latency, which is exactly backward for a latency-sensitive OLTP workload, so tune connection-pool concurrency against the latency target, not just against the maximum IOPS the device can theoretically sustain. RAID 5/6's parity write penalty (a single logical write can become several physical reads and writes to compute and store parity) makes it a poor choice under a random-write-heavy OLTP load even though its capacity efficiency looks attractive on paper.
Design a streaming upload path for large files (multi-GB datasets, media, or model artifacts) that never loads the whole file into memory: chunked or multipart uploads straight to disk or object storage, resumability if a transfer is interrupted, backpressure so a slow disk or slow object store doesn't cause the service to OOM or saturate disk, and integrity verification (checksums) as data streams through. What would you change about this design for a Go service that specifically needs to maximize upload throughput under concurrent load?
Sample Answer
Approach
Stream in fixed-size chunks straight from the request body to the destination (disk or object storage) instead of buffering the whole file, checksum incrementally as bytes flow through rather than in a separate pass, track how many bytes have landed so an interrupted transfer can resume from that offset instead of restarting, and let a bounded concurrency limit (not an unbounded goroutine or thread per upload) be the backpressure mechanism under load.
Design
Never load the whole file into memory: read a fixed-size chunk (a few megabytes is typical), write it through immediately, and discard it before reading the next chunk, so peak memory use is bounded by the chunk size, not the file size, regardless of whether the file is 10MB or 10GB. Chunked or multipart upload straight to disk or object storage: for object storage specifically, most providers expose a multipart upload API (initiate, upload part N with its own ETag, complete) that maps naturally onto this same fixed-chunk read loop, each chunk becomes one part. Resumability: persist the highest successfully-written offset (or the list of successfully completed part numbers for multipart object storage) somewhere durable (a small metadata record, not just in-process memory), so a retry after a dropped connection can query that offset and resume from there instead of re-uploading bytes already safely stored. Backpressure: the destination write call itself provides natural backpressure for a single stream, if the write blocks because the disk or object store is slow, the next read from the source simply waits, so the service does not keep pulling data faster than it can be persisted; for many concurrent uploads, a bounded worker pool (a fixed-size semaphore or channel) caps how many uploads are in flight at once, so total memory use stays bounded even under a burst of concurrent requests. Integrity verification: compute a checksum (SHA-256 or a similar strong hash) incrementally as each chunk streams through, feeding the same bytes into both the destination writer and the hash function in one pass, rather than re-reading the whole file afterward to verify it, which would defeat the memory-bounded design.
Worked example (Go)
const chunkSize = 4 << 20 // 4 MiB per chunk: never buffer the whole object
// streamChunks reads src in chunkSize pieces and writes each straight
// through to dst while it reads, returning a hex sha256 of the whole
// stream. Because writes happen inline with reads, a slow or blocked
// destination stalls the next Read call automatically: that stall IS
// the backpressure, no separate signalling channel needed for one stream.
func streamChunks(dst io.Writer, src io.Reader) (string, int64, error) {
h := sha256.New()
w := io.MultiWriter(dst, h)
buf := make([]byte, chunkSize)
var total int64
for {
n, rerr := src.Read(buf)
if n > 0 {
written, werr := w.Write(buf[:n])
total += int64(written)
if werr != nil {
return "", total, fmt.Errorf("write at offset %d: %w", total, werr)
}
}
if rerr == io.EOF {
break
}
if rerr != nil {
return "", total, fmt.Errorf("read at offset %d: %w", total, rerr)
}
}
return hex.EncodeToString(h.Sum(nil)), total, nil
}
// uploadConcurrent fans independent files out to a bounded worker pool.
// maxInFlight is the concurrency-level backpressure knob for the
// multi-upload case: unbounded goroutines-per-upload wins a
// microbenchmark and then exhausts memory or file descriptors under
// real concurrent load.
func uploadConcurrent(paths []string, destDir string, maxInFlight int) map[string]string {
sem := make(chan struct{}, maxInFlight)
var wg sync.WaitGroup
var mu sync.Mutex
results := make(map[string]string)
for _, p := range paths {
wg.Add(1)
go func(p string) {
defer wg.Done()
sem <- struct{}{} // blocks once maxInFlight are in flight
defer func() { <-sem }()
src, err := os.Open(p)
if err != nil {
return
}
defer src.Close()
dst, err := os.Create(filepath.Join(destDir, filepath.Base(p)))
if err != nil {
return
}
bw := bufio.NewWriterSize(dst, chunkSize)
sum, _, err := streamChunks(bw, src)
if err == nil {
bw.Flush()
mu.Lock()
results[p] = sum
mu.Unlock()
}
dst.Close()
}(p)
}
wg.Wait()
return results
}
Run against six ~9MB source files with maxInFlight=3, each result's SHA-256 checksum was independently recomputed by reading the destination file back and compared to what streamChunks produced inline:
file0.bin: checksum_match=true
file1.bin: checksum_match=true
file2.bin: checksum_match=true
file3.bin: checksum_match=true
file4.bin: checksum_match=true
file5.bin: checksum_match=true
all_checksums_match: true
What changes for a Go service maximizing throughput under concurrent load
maxInFlight becomes the primary tuning knob: too low under-utilizes available disk/network bandwidth, too high causes goroutines to pile up waiting on a slow destination and inflates memory (each blocked goroutine still holds its chunk buffer); size it from measured throughput per upload and the destination's actual concurrent-write capacity, not a guess. Reuse chunk buffers across uploads with sync.Pool rather than allocating a fresh chunkSize buffer per upload, since allocation and garbage collection of large buffers under high concurrency becomes a real throughput cost at scale (garbage collection, the Go runtime's automatic memory reclamation, has more work to do the more short-lived large objects it must track). For multipart uploads to object storage specifically, upload multiple parts of the SAME file concurrently (not just multiple files concurrently), since a single large file's throughput is otherwise capped by one sequential part-upload stream even while overall service concurrency looks high. Use io.CopyBuffer or the pattern above rather than ioutil.ReadAll anywhere in the path, since the latter reintroduces full in-memory buffering and defeats the design's whole point.
Trade-offs and pitfalls
Incremental checksumming means the destination receives unverified bytes as they stream; if integrity must be confirmed before the object is considered durable, either use a storage API that verifies a provided checksum against what it received (many object stores support this natively as part of the multipart-complete call) or accept a brief window where a corrupted upload is only caught after the fact and must be re-uploaded. Persisting resume state adds its own reliability requirement: if the resume-offset record itself is lost or inconsistent with what actually landed at the destination, resuming from a stale offset can either skip bytes or duplicate them, so treat the offset record with the same durability care as the data itself. Bounding concurrency for throughput requires real measurement (vary maxInFlight and measure actual aggregate throughput and destination-side error rate) since the optimal value depends on the destination's own concurrency limits, not just the source service's own capacity.
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.
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.
Given two storage device families, traditional HDD and NVMe SSD, explain which you would choose for: (a) large sequential media archival writes, (b) OLTP workloads with small random writes, (c) time-series ingestion combined with compaction. Discuss cost, latency, IOPS, throughput, and write-amplification trade-offs.
Sample Answer
Direct answer
Choose NVMe (Non-Volatile Memory Express, a solid-state storage interface built for low-latency, high-parallelism flash access) for the online transaction processing (OLTP, transactional database work with many small concurrent random reads/writes) workload and the time-series-with-compaction workload, both are dominated by random I/O and latency sensitivity where NVMe's advantage is largest; a traditional hard disk drive (HDD, spinning-platter mechanical storage) is a reasonable and often more cost-effective choice for large sequential archival writes, where NVMe's latency advantage matters least.
(a) Large sequential media archival writes: HDD
Archival writes are large, sequential, and not latency-sensitive (nobody is waiting on a single archival write to complete within milliseconds); HDDs achieve respectable sequential throughput (commonly in the 150-250MB/s range for modern drives) at a fraction of NVMe's cost per gigabyte, and archival workloads care about cost-per-terabyte far more than latency or IOPS. NVMe's main advantages, low random-access latency and high IOPS, are simply not exercised by a sequential write pattern, so paying its cost premium here buys nothing the workload actually uses.
(b) OLTP with small random writes: NVMe
OLTP workloads are dominated by many small, concurrent, random reads and writes with strict latency expectations (users and transactions waiting in real time); an HDD's mechanical seek time (the physical head movement between non-sequential locations on the platter, typically several milliseconds per seek) makes random I/O dramatically slower than sequential I/O on the same device, often by one to two orders of magnitude in achievable IOPS (I/O operations per second, how many individual read/write operations a device can complete each second). NVMe has no mechanical seek at all and is built specifically for high queue-depth, low-latency random access, making it the clear choice whenever the access pattern is random and latency-sensitive, which OLTP always is by nature.
(c) Time-series ingestion combined with compaction: NVMe
Time-series ingestion itself is often sequential-write-friendly (append-mostly), which might suggest HDD, but compaction (the background process many time-series and log-structured storage engines run to merge and reorganize on-disk data files) generates substantial additional random and mixed read/write I/O on top of the ingestion writes, and that background I/O directly competes with foreground query and ingestion latency. NVMe's high IOPS and low latency absorb this compaction overhead without degrading foreground performance nearly as much as an HDD would, where compaction I/O would visibly compete with and slow down both ingestion and queries.
Trade-offs: cost, latency, IOPS, throughput, write amplification
Cost: HDD wins decisively on cost per gigabyte, which is why it remains the right choice for (a) and for any workload where capacity, not speed, is the binding constraint. NVMe costs meaningfully more per gigabyte but that premium buys latency and IOPS that (b) and (c) cannot function well without. Latency: NVMe's random-access latency is typically in the tens-of-microseconds range versus an HDD's single-digit-to-double-digit milliseconds for a random seek, a difference of roughly two to three orders of magnitude that matters enormously for (b) and (c) and not at all for (a). IOPS: NVMe sustains vastly higher random IOPS than HDD because it has no mechanical seek penalty and supports much deeper command queuing (NVMe's queue depth can reach thousands versus a traditional SATA/SAS HDD's much shallower queue). Throughput: for pure large sequential transfers, the throughput gap between a fast HDD and NVMe is much smaller proportionally than the IOPS/latency gap, which is exactly why (a) tolerates HDD well. Write amplification (the effect where the physical bytes written to flash exceed the logical bytes the application asked to write, because flash must erase and rewrite in larger blocks than it programs in) is an NVMe/SSD-specific concern with no HDD equivalent; a write-heavy random workload like (b) and the compaction-heavy workload in (c) both increase write amplification, which affects the SSD's endurance/lifespan and can reduce effective write throughput as the drive fills, an over-provisioning margin and a filesystem/database tuned to reduce small random writes (batching, larger block sizes where the workload allows it) both help manage this.
Trade-offs and pitfalls
The most common mistake is picking storage based on throughput or capacity alone and ignoring latency and IOPS, which are what actually determine OLTP and compaction-heavy performance; a spec sheet's MB/s number is close to irrelevant for workload (b). The second common mistake is under-provisioning NVMe capacity for a write-heavy workload without accounting for write amplification, which can quietly erode both endurance and effective throughput well before raw capacity is exhausted.
Unlock Full Question Bank
Get access to all 10 System Resource & I/O Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.