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 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.
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.
Medium: Create a systemd service unit for a Python web application that relies on a database. Requirements: start only after network and db.target, run as 'webapp' user, set LimitNOFILE=10000, restart on-failure with exponential backoff, and ensure stdout/stderr go to the journal. Provide the unit file and explain the restart/backoff approach.
Sample Answer
Approach
Start from the minimal set of directives a service actually needs to run and be managed by systemd (systemd is the standard Linux init system and service manager on most modern distributions), then layer on the ordering, resource, and reliability requirements one at a time so each one is easy to justify on its own.
A bare-minimum unit that just runs the app looks like this:
# /etc/systemd/system/webapp.service (minimal starting point)
[Unit]
Description=Example Python web application
[Service]
ExecStart=/usr/bin/python3 /opt/webapp/app.py
[Install]
WantedBy=multi-user.target
That alone is enough for systemd to start, stop, and status the service, but it has none of the ordering, resource, or restart behavior the requirements ask for.
Full unit file
# /etc/systemd/system/webapp.service
[Unit]
Description=Example Python web application
After=network-online.target db.target
Wants=network-online.target db.target
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
Type=simple
User=webapp
Group=webapp
WorkingDirectory=/opt/webapp
ExecStart=/usr/bin/python3 /opt/webapp/app.py
LimitNOFILE=10000
Restart=on-failure
RestartSec=2
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
Key points
After=network-online.target db.target orders startup so the unit only starts once networking is actually up (network-online.target, not the weaker network.target, which only means the network stack is initialized, not that an interface has an address yet) and the database target has been reached. Wants= on the same two targets is a soft dependency: if db.target fails to come up, webapp.service still tries to start rather than being blocked forever, which is usually the right default for a service that should retry its own database connection rather than depend on systemd to gate it. User=webapp / Group=webapp drop root privileges for the running process. LimitNOFILE=10000 raises the per-process open-file-descriptor ceiling above the common distro default of 1024, which a web app juggling many concurrent sockets and log/temp files needs. StandardOutput=journal / StandardError=journal route both streams to the systemd journal (journalctl -u webapp) instead of a separate log file the service would have to manage itself.
Restart and backoff approach
Restart=on-failure restarts the service only on a non-zero exit or crash, not on a clean systemctl stop. RestartSec=2 is the delay before each restart attempt. Plain systemd RestartSec is a fixed delay, not a true exponential backoff, so the real backoff protection comes from StartLimitIntervalSec=300 combined with StartLimitBurst=5: if the service restarts 5 times within any rolling 300-second window, systemd stops trying and marks the unit failed, which prevents an infinite fast-restart loop from hammering the database it depends on. On systemd v254 and newer, RestartSteps= and RestartMaxDelaySec= can be added to make RestartSec itself increase on each consecutive failure (a genuine exponential-style backoff), but since the deployed systemd version is not guaranteed, the StartLimitBurst circuit breaker above is the version-portable way to satisfy the "restart on-failure without a restart storm" requirement; add RestartSteps as a refinement once the target OS version is confirmed.
Trade-offs and pitfalls
After=/Wants= on db.target only helps if something on the box actually defines and reaches db.target (a database running as its own systemd unit, or a synthetic target created for this purpose); if the database is remote or unmanaged by systemd, this ordering does nothing and the application must retry its own connection instead. Restart=on-failure will not restart a process that hangs without exiting; pair it with WatchdogSec= and an sd_notify heartbeat from the app if hangs (not crashes) are the actual failure mode you are protecting against. Setting LimitNOFILE above the system-wide fs.file-max sysctl has no effect, since the kernel-wide ceiling wins; check /proc/sys/fs/file-max if 10000 does not seem to take effect. Finally, StartLimitBurst/StartLimitIntervalSec live under [Unit], not [Service], a common typo that silently disables the restart-storm protection.
Explain how cgroups and ulimits can be used to enforce CPU and memory limits for processes and containers. Give examples of how to set MemoryMax and CPUQuota in a systemd unit file and cpu/memory limits for Docker. Explain how the OOM killer interacts with cgroup-limited processes.
Sample Answer
Direct answer
ulimits are per-process resource ceilings enforced by the kernel at the individual process level (set via the setrlimit() syscall, commonly configured through the ulimit shell builtin or /etc/security/limits.conf), while cgroups (control groups, a kernel mechanism for grouping processes together) enforce an aggregate resource budget across an entire group of processes collectively. For a single-process, single-threaded tool, a ulimit might be enough. For a container or a systemd service that can spawn helper processes, cgroups are the right tool, because they cap the group's combined usage rather than each process individually.
Structured elaboration
ulimits. A ulimit is set on a process (and inherited by its children) and bounds a single resource for that one process, for example RLIMIT_NOFILE (max open file descriptors) or RLIMIT_AS (max address space). The key limitation: if a service forks multiple worker processes, each one gets its own independent ulimit ceiling, there's no shared budget across them, so ulimits don't actually cap the service's total resource footprint the way you'd usually want for a multi-process daemon.
cgroups. A cgroup enforces a shared ceiling across every process placed in it, regardless of how many processes or threads that group contains. This is why systemd services and containers use cgroups for real capacity control: MemoryMax=2G on a systemd unit means the whole service, all its child processes combined, cannot exceed 2 GB, not that each process individually gets 2 GB.
How the OOM killer interacts with cgroup-limited processes. Without cgroup memory limits, a runaway process competes in the global out-of-memory killer's process-wide scoring, which can end up killing an unrelated critical process based on its oom_score. With a cgroup memory.max set, a group that would exceed its limit is first pushed into reclaim inside the group, and only when reclaim cannot free enough does the kernel invoke the OOM killer scoped to that specific cgroup: it picks the highest-scoring process within that group to kill, containing the damage to the offending service instead of letting it risk taking down something unrelated on the same host. This is one of the strongest practical arguments for setting MemoryMax on every service rather than relying on ulimits or hoping nothing leaks.
Worked example
A systemd unit for an HTTP server, myserver, with CPU and memory limits applied:
[Service]
ExecStart=/usr/local/bin/myserver
MemoryHigh=1750M
MemoryMax=2G
CPUQuota=150%
MemoryMax=2G is the hard cgroup v2 memory.max limit: if the group's total memory usage would exceed it, the kernel invokes the cgroup-scoped OOM killer against a process inside that group. MemoryHigh=1750M sets a softer memory.high ceiling below that: crossing it triggers aggressive reclaim and throttling within the group as a warning zone, before you hit the hard kill boundary, giving the service a chance to shed load or free memory gracefully. CPUQuota=150% caps the unit's cgroup at 1.5 CPU cores' worth of time; under the hood this is expressed as a quota and period on cpu.max (for example 150ms of CPU time allowed per 100ms period).
The closest Docker equivalents:
docker run --memory=2g --memory-reservation=1750m --cpus=1.5 myimage
--memory maps to the same hard memory.max, and --cpus=1.5 maps to the same CPU quota mechanism as CPUQuota=150%. --memory-reservation is the one that does not line up: on a cgroup v2 host the runtime (runc) writes it to memory.low, which is a best-effort reclaim protection floor, usage below it is shielded from reclaim while unprotected cgroups still have memory to give back, rather than a memory.high-style throttling ceiling that pushes back on the group once it grows past the threshold. The two point in opposite directions: memory.high acts on the group above the number, memory.low protects the group below it. The "soft limit" name is inherited from cgroup v1, where the same flag set memory.soft_limit_in_bytes and did behave as a reclaim-first ceiling under contention. Docker's CLI exposes no direct memory.high equivalent, so if you want the graceful-throttling behaviour of MemoryHigh for a container, set it on the container's cgroup, for example by running it under a systemd slice that carries MemoryHigh=, or by writing memory.high in the container's cgroup path.
Now suppose this service leaks memory and climbs past 2 GB. The kernel invokes the OOM killer scoped to this service's own cgroup, killing the leaking process while an unrelated database process running elsewhere on the same host, outside this cgroup, is never considered a candidate and keeps running untouched. That containment is the concrete payoff of the group-level limit: the blast radius of the leak stops at the cgroup boundary instead of spreading to whichever process the kernel's global scoring would otherwise have picked.
Trade-offs and pitfalls
Setting MemoryMax without also setting a MemoryHigh softer threshold means the service goes straight from "fine" to "killed" with no graceful degradation window; most production configurations set both. Also, CPUQuota throttles a bursty service uniformly across the period, which can turn a legitimate short burst (fine on an unconstrained box) into visible latency; if bursts matter, consider a longer accounting period or a higher quota with monitoring rather than a tight one set from a single peak-usage measurement.
Hard: On a NUMA system, a database exhibits poor performance after a kernel upgrade. Explain how NUMA misplacement can lead to this regression and provide a stepwise approach (commands and experiments) to detect and remediate NUMA-related memory allocation issues for the DB process.
Sample Answer
Mechanism: how a kernel upgrade breaks NUMA placement
NUMA (Non-Uniform Memory Access: each CPU socket has its own local memory, and reaching another socket's memory over the interconnect costs extra latency) placement is governed by kernel defaults that can change silently across an upgrade. Two common culprits: the default value of vm.zone_reclaim_mode (historically some distributions shipped it on by default on certain kernel versions, which prefers reclaiming local memory over allocating remote memory, and can end up thrashing the page cache instead of simply placing the allocation remotely) and automatic NUMA balancing (kernel.numa_balancing), the kernel's own background feature that migrates pages and threads toward each other over time, which can become more or less aggressive between kernel releases and add scanning overhead the database was not tuned to expect. Either change can quietly break a database's previously stable locality assumptions without anyone touching the database's own configuration.
Stepwise detection and remediation
- Confirm the regression is actually NUMA-related before chasing it: check
numastat -p <db_pid>now, and if a historical baseline exists, comparenuma_hit/numa_miss/other_nodebefore and after the upgrade. - Rule out a hardware or firmware change at the same maintenance window:
numactl --hardwareshould show the same topology as before; if BIOS NUMA interleaving settings were also touched during the same maintenance, that is a competing explanation worth ruling out first. - Diff the relevant sysctls against a known-good baseline:
sysctl kernel.numa_balancing,sysctl vm.zone_reclaim_mode, andcat /sys/kernel/mm/numa_balancing. A silent default change here is the most common root cause for this exact symptom (regression right after an otherwise routine kernel upgrade). - Confirm the database's CPU affinity mask is still actually applied:
taskset -pc <pid>. An upgrade to the init system or container runtime can drop an affinity setting that used to be set at boot without any visible error. - Run a controlled experiment: force strict locality on a canary instance with
numactl --cpunodebind=N --membind=Naround the database's startup, and measure whether latency recovers. This isolates whether placement is genuinely the cause versus something else that coincidentally changed with the kernel. - If automatic NUMA balancing overhead is the culprit, look for elevated
numa_pages_migratedin/proc/vmstatalongside CPU time in kernel migration threads; disable it (echo 0 > /proc/sys/kernel/numa_balancing) and re-pin statically instead, trading the kernel's adaptive behavior for a known-good fixed layout. - Make the fix durable: pin the database explicitly through the systemd unit (
AllowedCPUs=or anumactlwrapper) rather than relying on kernel defaults, and record the required sysctl values in configuration management so drift-detection catches the next kernel upgrade's default change before it pages someone.
Unlock Full Question Bank
Get access to all System Resource & I/O Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.