KatInterview

Tracing a 4 GiB Allocation, Swap Stalls, and the Cost of Inlining

System DesignModel answer
HardModel answerSystem Designoperating-systemsvirtual-memorylinux

Last updated

Walk through how a huge allocation becomes virtual and physical memory on Linux, why swap hurts tail latency, and what C++ inline means for linkage and the CPU.

Memory, Paging, and Inlining in a Latency-Sensitive C++ Service

You are building a C++ service on Linux whose hot loop must finish in a few microseconds, with a very tight 99.99th-percentile latency. Answer the three parts below, and be specific about syscalls, thresholds, and rough costs.

Part 1: What happens on a 4 GiB allocation

Your program runs std::vector<char> buf(4ULL << 30); or malloc(4ULL << 30).

  1. How does the allocator choose between extending the heap with brk/sbrk and creating an anonymous mmap region?
  2. What does the kernel hand back right away? How do virtual address space and physical RAM differ at that moment?
  3. Distinguish minor from major page faults. Compare filling the buffer sequentially with touching it sparsely.

Part 2: Memory pressure, swap, and tail latency

  1. How does the kernel's reclaim logic treat anonymous pages versus file-backed page-cache pages?
  2. What is thrashing, and why can one swapped-out page turn a microsecond-scale loop iteration into a multi-millisecond outlier?
  3. Compare turning swap off entirely with using mlock/mlockall. What does each guarantee, and what does each leave open?

Part 3: inline in C++

  1. What is the language-level purpose of inline, particularly with respect to the One Definition Rule across translation units?
  2. How do GCC and Clang actually treat the keyword when optimizing? How does link-time optimization (LTO) change whether you need it?
  3. Discuss the hardware costs and benefits of aggressive inlining: L1 instruction cache footprint, register allocation and spilling, and branch prediction.

Give a structured answer with trade-offs, and point out common misconceptions.

Hints

Hint 1

For Part 1, ask whether `std::vector` merely reserves memory or also writes to it, and compare that with plain `malloc`. Then count how many 4 KiB pages are in 4 GiB.

Hint 2

For Part 2, list what the kernel can do with a page when it needs the frame back: drop it, write it out then drop it, or nothing. Then ask which of those is possible for your own executable's code if swap is off.

Hint 3

For Part 3, separate what `inline` means to the linker from what it means to the optimizer. For the hardware side, think of three separate resources that get stressed when code is duplicated at many call sites.