Virtual Memory and I/O
1. Executive Summary
Virtual memory gives each process an isolated, contiguous address space mapped by hardware and the OS onto physical RAM and backing store. Paging enables overcommit, copy-on-write, memory-mapped files, and efficient process creation. Block and file I/O move data between persistent storage and memory through layered kernel subsystems buffered, direct, or memory-mapped.
This chapter covers page tables, TLBs, page faults, swapping, mmap, the page cache, and how I/O paths interact with schedulers and storage latency. Understanding virtual memory explains OOM kills, mmap performance cliffs, and database buffer pool behavior.
Key takeaway: Every pointer your application dereferences passes through virtual-to-physical translation — and every I/O path competes for the same memory bandwidth.
2. Why This Topic Matters
Principal architects debug:
- Why did the JVM get OOM-killed despite "free" memory on the node?
- mmap vs. read/write for log ingestion?
- How do huge pages help databases?
- What causes major vs. minor page faults?
Links to Storage Engine Fundamentals and Write-Ahead Log.
3. Problems Being Solved
| Problem | Description |
|---|---|
| Isolation | Processes cannot access each other's memory |
| Sparse address spaces | Allocate large virtual regions without physical RAM |
| Shared libraries | Map same code read-only into many processes |
| Durability | Persist data via block I/O and filesystems |
| Performance | Page cache amortizes disk reads |
4. Assumptions and System Model
- Paged virtual memory with hardware MMU on x86-64/ARM.
- 4 KiB base pages; huge pages (2 MiB, 1 GiB) optional.
- Linux examples:
mmap, page cache,swap,vm.overcommit_memory. - Storage as block devices behind filesystems or direct device access.
5. Essential Terminology
| Term | Definition |
|---|---|
| Virtual address | Address used by program |
| Physical address | Location in RAM |
| Page table | Maps virtual pages to physical frames |
| TLB | Cache of page table entries |
| Page fault | Access to unmapped or protected page triggers kernel handler |
| Major fault | Requires loading from disk |
| Minor fault | Mapping exists; no disk I/O |
| Copy-on-write (COW) | Share pages until write |
| mmap | Map file or anonymous memory into address space |
| Page cache | Kernel cache of file pages in memory |
| Swap | Evict cold pages to disk backing store |
| Direct I/O | Bypass page cache (O_DIRECT) |
6. Core Mechanism
Explanation: The MMU translates virtual to physical addresses. TLB hits are fast; misses walk page tables. If the page is not resident, a major page fault reads from disk via the page cache.
7. Step-by-Step Walkthrough
fork() + exec() launching a service:
Step 1 — fork. Child inherits parent's page table entries marked copy-on-write.
Step 2 — Write in child. COW fault allocates new physical page for modified page.
Step 3 — exec. Replace address space; load binary via page cache; demand paging brings code pages on first execution (minor faults).
Step 4 — mmap WAL file. Database maps write-ahead log; appends cause page cache dirty pages; fsync pushes to storage.
Step 5 — Memory pressure. Kernel reclaims clean page cache first; may swap anonymous pages; OOM killer if overcommit fails.
8. Invariants and Guarantees
| Property | Guarantee |
|---|---|
| Process isolation | Without shared mappings, cannot access other's mapped memory |
| CoW on fork | Reads share until write |
| Mapped file coherence | msync/fsync semantics for durability (filesystem-dependent) |
Not guaranteed: Unlimited virtual allocation maps to RAM; malloc success implies future OOM safety.
9. Failure Scenarios
Scenario 1: OOM Killer
Node overcommitted; spike in allocations; kernel kills largest process (often Java or database).
Mitigation: Set container memory limits; tune overcommit; use heap limits; monitor node_memory_MemAvailable.
Scenario 2: Swap Thrashing
RAM exhausted; constant paging; latency collapses.
Mitigation: Disable swap on latency-sensitive DB nodes; right-size memory; reduce footprint.
Scenario 3: mmap Random Write Amplification
Random updates to huge mmap file cause many page faults and cache pressure.
Mitigation: Sequential writes, appropriate record size, or traditional buffered I/O with application buffer.
Explanation: Anonymous mmap or first heap touch triggers demand paging — the kernel allocates a physical frame and updates page tables. This is a minor fault if no disk I/O is required.
Extended Deep Dive: Anonymous Memory vs File-Backed
Anonymous pages (heap, stack) have no file backing — swap to swap partition/file if enabled. File-backed pages (mmap, page cache) can be reclaimed by dropping clean cache or writing dirty cache to file. Locked memory (mlock) prevents eviction — use sparingly for real-time or database buffers; failure to lock may indicate ulimit RLIMIT_MEMLOCK.
Transparent Huge Pages (THP): Kernel collapses small pages into huge pages automatically — can help or hurt databases (latency spikes during collapse). Many DB vendors document disable or madvise preferences — follow primary source for your engine.
Extended Deep Dive: I/O Schedulers and NVMe
Legacy CFQ scheduler reordered rotational disk requests; none or mq-deadline common on NVMe with deep queues. Misapplied rotational tuning on flash is historical footgun. Cloud EBS/network storage adds queue depth limits — application concurrency must match device capability, not only CPU.
10. Performance Characteristics
TLB pressure hurts when working set spans many pages — huge pages reduce entries needed.
Page cache makes repeated reads fast; cold reads pay disk latency (orders of magnitude slower than RAM — qualitative).
O_DIRECT avoids double buffering for databases that manage their own cache.
11. Scalability Limits
- RAM bounds hot data.
- Page table memory for very large mappings.
- I/O bandwidth to storage and network block devices.
- fsync rate limits durable write throughput.
12. Operational Considerations
Tune: vm.swappiness, transparent huge pages (workload-dependent — databases often disable THP), dirty_ratio for writeback.
Monitor: page faults, major faults, OOM events, disk await, page cache hit ratio (indirect via I/O).
13. Security Considerations
ASLR randomizes mappings; W^X prevents writable+executable pages.
Meltdown/Spectre mitigations affect syscall and page table isolation (KPTI).
mmap of sensitive files needs permission checks; shared memory regions cross trust boundaries in containers.
14. Cost Considerations
Over-provisioning RAM avoids swap/OOM but increases cloud bill. Tiered storage trades latency for cost.
Efficient page cache use reduces IOPS charges on cloud disks.
15. Production Implementations
| System | Pattern |
|---|---|
| PostgreSQL | shared_buffers + OS page cache; optional huge pages |
| LMDB | mmap entire database |
| Kafka | Page cache relies on sequential log read |
| Elasticsearch | mmap for Lucene segments (with caveats) |
| Containers | cgroup memory limits + OOM behavior |
Extended: mmap vs read/write Decision Framework
Choose mmap when: large read-mostly files, sequential or random read within mapped region, OS page cache desired, multiple processes share read-only mapping. Choose read/write or direct I/O when: fine-grained durability control, streaming writes with bounded memory, portability across OS, error handling simplicity, or working set exceeds address space sanity. Databases often combine: mmap for read segments, append-only log with explicit fsync for writes.
Extended: VFS and Block Layer Path
Read syscall traverses VFS → filesystem (ext4, xfs) → page cache → block layer → driver → device. Direct I/O aligns buffers to block size and bypasses page cache — database manages consistency. Async I/O (libaio, io_uring) overlaps submission with computation. Each layer adds latency variance — distributed storage adds network block device latency on top.
Extended: Zombie and Orphan Processes
Zombie (defunct) processes hold PID until parent calls wait() — PID exhaustion possible if parent bug. Init/systemd reaps orphaned children. In containers, PID 1 must reap zombies — use minimal init (tini, dumb-init) if application does not handle SIGCHLD. Operational symptom: cannot fork new processes despite low memory — check ps aux | grep defunct.
16. Alternatives and Tradeoffs
| Approach | Pros | Cons |
|---|---|---|
| Buffered I/O | Kernel optimizes readahead | Extra copy |
| mmap | Zero-copy feel | Page faults, complex error handling |
| Direct I/O | Predictable cache | Alignment constraints |
| Huge pages | Fewer TLB misses | Allocation friction |
| Swap enabled | Survive spikes | Latency disaster |
17. Common Misconceptions
-
"Virtual memory is unlimited." — Backed by RAM, swap, or nothing (OOM).
-
"mmap is always faster." — Depends on access pattern.
-
"Free memory is wasted." — Linux uses it for page cache (reclaimable).
-
"Minor faults are free." — Cheaper than major, not zero cost.
-
"Container limit = JVM heap limit." — Need headroom for native, metaspace, page cache.
18. Principal Architect Perspective
Define memory limits policy for platforms; document huge page setup for stateful services; require capacity models including page cache and replication buffers.
Extended: Multi-Level Page Tables
x86-64 uses 4-level (and optionally 5-level) page tables. Each virtual address translation may require multiple memory accesses for page table walks on TLB miss — page walk cache mitigates but does not eliminate cost. Very large sparse address spaces (many mappings, scattered access) increase TLB pressure disproportionate to RSS. Databases mapping terabytes virtually but touching gigabytes physically still pay translation costs on scattered access.
Extended: Copy-on-Write in Containers and Fork
Container image layers use overlay filesystems with CoW — writes to upper layers duplicate blocks. fork() in Linux after clone flags shares memory until write — relevant for pre-forking web servers (historical Apache model). Understanding CoW explains memory usage spikes when processes diverge after fork — monitoring RSS vs. PSS (proportional set size) clarifies actual memory pressure in shared environments.
Extended: Page Cache Writeback Policy
Dirty pages accumulate until dirty_ratio or dirty_background_ratio triggers writeback flusher threads. Burst writes can saturate disk briefly; synchronous fsync bypasses lazy writeback for durability at latency cost. Architects sizing log pipelines must model fsync rate not just bytes/sec — many small fsyncs destroy throughput on rotational and some SSD configurations.
Extended: Memory Overcommit and OOM Scoring
Linux vm.overcommit_memory modes change whether malloc can succeed without guaranteed physical backing. Mode 0 heuristically allows overcommit; mode 2 strict caps commit. OOM killer selects victims by oom_score influenced by memory usage, cgroup limits, and oom_score_adj. In Kubernetes, container without memory limit runs as best-effort — can consume node memory until node-level OOM affects neighbors. Always set memory limits for multi-tenant nodes with headroom for kernel and page cache.
19. Architecture Review Exercise
A log analytics platform mmap's 10 TB of cold files per host with random access. Memory and latency are unstable. Propose architecture changes across I/O model, indexing, and hardware.
20. Whiteboard Explanation
"Each process sees virtual addresses. The MMU maps them to physical RAM via page tables cached in the TLB. Missing pages fault in from disk. fork uses copy-on-write. Files can be mmap'd into memory — reads hit the page cache. Under pressure, kernel reclaims cache or swaps, or OOM-kills. Databases tune huge pages and direct I/O to control latency."
Extended Walkthrough: Database Buffer Pool vs OS Page Cache
PostgreSQL shared_buffers holds relation pages in process memory. OS page cache also caches same underlying files if double-cached — wasted RAM. Tuning balances shared_buffers size against kernel cache reliance.
Direct I/O databases bypass page cache for data files in some configurations — predictable memory accounting. WAL still uses buffered I/O typically.
Checkpoint and writeback: Dirty shared_buffers flushed during checkpoint; spikes I/O. vm.dirty_* sysctl affects concurrent OS-level writeback from other processes — noisy neighbor on shared nodes.
Principal decision: Document memory limit = heap + shared_buffers + connection overhead + autovacuum + headroom; do not assume page cache is free for colocated pods.
Extended Failure Scenario: Container Memory Limit OOM vs Node OOM
Pod memory limit 4Gi; JVM max heap 4Gi — native memory, metaspace, thread stacks exceed limit; cgroup OOM kills container despite "heap not full." Fix: MaxRAMPercentage respecting cgroup; leave headroom; Native Memory Tracking. Distinguish from node-level OOM affecting multiple pods.
21. Interview Questions
-
What is virtual memory and why use it?
-
Major vs. minor page fault?
-
Explain copy-on-write after fork.
-
How does the TLB relate to page tables?
-
What are huge pages and when help?
-
mmap vs. read/write tradeoffs?
-
What is the page cache?
-
Why might a process be OOM-killed despite free memory on the system?
-
What does
fsyncguarantee? -
Direct I/O use cases?
-
How do container memory limits interact with the page cache?
-
Explain demand paging.
22. Interview Follow-Ups
-
After Q8: "Explain cgroup memory accounting vs. host free." — Limit includes cache charged to cgroup; host free may be mostly cache.
-
After Q6: "When is mmap wrong for a database?" — Random write, portability, error handling, huge VM.
-
Principal: "OOM killed production DB — organizational prevention?" — Memory requests/limits standards, load tests, OOM drill runbooks.
22A. Production Low-Level Design (Interview + Game Day)
Design a mmap-backed immutable blob cache with page-fault metrics and madvise policy. Production LLD and Game Day Standard.
Control vs data plane
| Plane | Role |
|---|---|
| Control | madvise policy, THP settings, fault dashboards |
| Data | mmap read-only artifacts; demand paging on access |
API: OpenBlob(id) → MmapView; warm with MADV_WILLNEED optional.
Step-by-step flow:
| Step | Mechanism | Ops hook |
|---|---|---|
| 1 | mmap avoids copy | Kernel page cache shared |
| 2–3 | Minor fault fills PTE | Track minor/major rate |
| 4–5 | Cold access → major fault | madvise WILLNEED warm |
- SLO: p99 blob open < 50ms warm; alert major fault spike post-deploy
22B. Game Day Playbooks
| # | Drill | Inject | Detect | Mitigate | Verify |
|---|---|---|---|---|---|
| GD-1 | Cold start spike | Deploy new blob | Major faults ↑ | MADV_WILLNEED warm | p99 stable |
| GD-2 | Swap storm | Memory pressure | swap in/out | mlock hot blobs / RAM | No swap on path |
| GD-3 | THP collapse fail | Disable THP | dTLB misses | Enable THP for large maps | TLB stable |
| GD-4 | Leaked mappings | Forgot munmap | RSS creep | Lifecycle audit | RSS flat |
GD-1 — Latency spike after new artifact deploy
23. Strong Answer Example
Question: "Explain page faults in production and how you'd debug latency spikes."
Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—minor vs major faults + swap, not "disk is slow."
Student interview script (PRACTICE)
P — Problem framing
"Minor faults populate PTEs; major faults pull pages from disk. Latency spikes often from cold mmap after deploy, THP issues, or swap—not always bad disk."
R — Requirements
| Type | Requirement |
|---|---|
| Perf | p99 blob read < 50ms |
| Ops | Fault counters in dashboards |
| Safety | Read-only mmap for immutable |
A — Assumptions
| Assumption | Why it matters |
|---|---|
| Immutable blobs | MAP_SHARED safe |
| Page cache shared | Multiple pods benefit |
| Swap enabled on node | Risk for latency |
C — Capacity (sketch)
50GB blob; 4KB pages → 12.5M PTEs
Cold read: major faults dominate
Warm: minor only
T — Topology (draw this)
Step-by-step flow:
| Step | Claim |
|---|---|
| 1 | Check /proc/self/stat fault counts |
| 2 | Correlate deploy time |
| 3 | Warm or madvise |
I — Invariants
"Immutable blobs never written via mmap."
C — Constraints
| Constraint | Response |
|---|---|
| Swap pressure | mlock or isolate nodes |
| Huge blob cold | Warm in CD |