← Runtimes
Runtimes

Virtual memory and the allocator

Follow memory from the operating system to the value you created.

Live values, allocator storage and resident pages are different measures of process memory.

Outcome

Explain how a request travels from your code through the allocator to operating-system pages, predict when memory becomes resident, and say why freeing values may not lower resident memory.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Page
A unit of OS virtual-memory mapping. Its size depends on the platform and mapping; the teaching model fixes it at 4096 bytes.
Reserved
Address space the process has set up, for example with mmap, whether or not physical memory backs it yet.
Resident (RSS)
Memory currently resident for this process’s mappings, including shared pages. RSS is not a count of live objects or exclusively owned physical bytes.
Allocator
The library code (malloc, the Go runtime, V8, Rust’s global allocator) that cuts pages into the small blocks your code requests.
Size class
A fixed block size an allocator uses for requests up to that size, so equal blocks can share a page.
mmap
The system call that maps new pages into the address space; allocators use it to obtain memory.

Three different memory accounts

An allocator supplies storage for values; the operating system manages virtual-memory mappings in units called pages. Live bytes describe storage still used by values. Reserved virtual space describes mappings the process has arranged. Resident memory (RSS) counts pages currently resident for its mappings, including shared pages; it is not a count of live objects or exclusively owned bytes.

A common small-object allocator rounds requests into size classes and serves slots from memory it holds; larger requests can follow another path. The OS supplies mappings through facilities such as mmap. Fresh anonymous zero memory can be demand-paged, but prefaulting, allocator reuse, page sizes and platform policies affect when backing pages are needed.

01From pages to values

Three layers between your value and physical memory

A map-tile service reserves room for a large tile index before traffic arrives. Later it evicts most cached entries, but its resident-memory dashboard barely falls. Before changing the cache limit, distinguish the bytes the cache still uses, the space its allocator holds and the pages the OS currently keeps resident.

For the tile-cache investigation, keep each layer’s counters separate while probing startup allocation and later eviction.

Who decides what
LayerUnitWhere you see it
Your codeValues and objectsLive bytes (heap profilers, runtime stats)
AllocatorSize-class slots in pages it holdsAllocator or runtime statistics
Operating systemMappings and currently resident pagesVmRSS/smaps; container totals use separate accounting

02Resident when touched

Allocating is not using

First isolate the sparse index’s startup allocation. The probe samples process VmRSS, creates a zero-filled 64 MiB buffer, then writes at a fixed 4096-byte stride and samples again. The stride is authored, not a measurement of the OS page size. VmRSS is approximate and includes unrelated process activity, so deltas can be noisy or negative; the Rust helper uses signed arithmetic for that reason.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { readFileSync } from 'node:fs';

/** Resident memory of this process in MiB, from Linux's /proc/self/status. */
function residentMiB(): number {
  const kib = Number(/VmRSS:\s+(\d+)/.exec(readFileSync('/proc/self/status', 'utf8'))![1]);
  return Math.round(kib / 1024);
}

const PAGE = 4096;
const SIZE = 64 * 1024 * 1024;

const start = residentMiB();
const buffer = new Uint8Array(SIZE);
const allocated = residentMiB();
for (let offset = 0; offset < SIZE; offset += PAGE) buffer[offset] = 1;
const touched = residentMiB();

console.log(`after allocating 64 MiB: +${allocated - start} MiB resident`);
console.log(`after writing one byte per page: +${touched - start} MiB resident`);
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
For the original recorded runner probe, predict the approximate RSS increase after creating the zero-filled 64 MiB buffer, before the stride-writing loop. This asks about that observation, not a language guarantee for every run.

03Giving memory back

Freed values are not freed pages

After the busy period, the service evicts cached entries. Storage can become reusable inside an allocator without its mappings disappearing. A non-moving allocator may keep a partly occupied page because the remaining value still needs its bytes. Empty pages can be retained, unmapped or have their backing discarded while the virtual mapping remains; RSS can also change through OS reclaim. The lab will choose one explicit release policy rather than infer all of this from one counter.

Use a non-moving allocator model that releases only completely empty pages. One resident 4096-byte page holds 32 values of 128 bytes. With no other activity, freeing 31 values lowers modeled resident memory by how much?

04Practice

Model an allocator’s pages

Build a diagnostic model for the tile cache: requested record bytes round into slots, writes make a model page resident, and the final free on a page releases that page. It uses 4096-byte pages and fixed classes, with allocation names unique while live and positive decimal integer requests. Oversized requests report too large. Its resident flag changes only by these commands; empty-page release is an authored policy, not a promise that a real allocator always returns every empty page.

A page allocator model

A small allocator model reserves pages and cuts them into size-class slots. Pick the size class, count which pages are resident, then decide when a page can go back to the operating system.

  1. easy · R-MEM-V4-1 Pick the size class
  2. medium · R-MEM-V4-2 Count resident pages
  3. hard · R-MEM-V4-3 Give pages back
Check this idea later
Assume a non-moving allocator with no unrelated RSS activity. A cache drops 80% of its small entries, spread evenly across its pages, while RSS stays flat. Which explanation fits?
In the lesson’s lazy-residency model, reserve a 1 GiB table without touching it, then write only the first 10 MiB. With no other activity or reclaim, how much is counted resident?
An allocator uses classes 16, 32, 64 and 128 bytes. A program stores one million 33-byte records. About how much memory do their slots use?
Sources
In the frontend Label process RSS separately from managed heap and buffer storage. Optional

The tile-cache dashboard needs to distinguish cache eviction from process-memory release. Its server can report Node memory counters, but a falling heap value and flat RSS answer different questions. These measurements describe one server process, not the browser or the whole deployment.

app/api/memory/route.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { memoryUsage } from 'node:process';

export const runtime = 'nodejs';

export function GET() {
  const { rss, heapUsed, arrayBuffers } = memoryUsage();

  return Response.json({ rss, heapUsed, arrayBuffers });
}

The Node App Router handler returns byte counts. heapUsed is used V8 heap, not an exact count of reachable tile entries; arrayBuffers includes ArrayBuffer backing storage, while RSS covers the wider resident process. These categories overlap and must not be added as independent totals. A response after eviction does not guarantee a collection or allocator release.

Sources: Node.js: process.memoryUsage,Next.js: Route Handlers,SvelteKit: server routes.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.