Sub topic 13
Shorter Pauses: Incremental, Parallel, and Concurrent GC
The earlier chapters described mark-and-sweep as one complete pass: stop the program, mark everything reachable, then sweep the rest. That description is correct, but a naive version of it causes a practical problem. While the collector runs, your JavaScript does not. On a heap of several hundred megabytes, one full stop-the-world collection can take tens or hundreds of milliseconds. That is long enough to drop animation frames in a browser or add visible latency to every request in a Node.js server.
This chapter explains how V8 shortens these pauses. V8 is the engine in Chrome and Node.js, and its modern collector was built under a project called Orinoco. The chapter assumes you already know mark-and-sweep and the young/old generation split from the previous chapters. You should also be able to run Node.js scripts from a terminal.
The Problem: Stop-the-World Pauses
A stop-the-world pause is any period when the engine halts JavaScript execution so the collector can work on the heap without interference. The browser renders a frame about every 16.7 ms at 60 frames per second, so a 50 ms pause drops roughly three frames. In a server, a pause delays every request that is waiting on the event loop at that moment.
Engines combine three techniques to deal with this. Each attacks the pause from a different side.
| Technique | What it changes | Main-thread pause | Total GC work |
|---|---|---|---|
| Stop-the-world | Nothing; GC runs all at once on the main thread | Longest | Lowest |
| Incremental | Splits the work into small steps interleaved with JavaScript | Many short pauses | Slightly higher |
| Parallel | Uses several threads at once during a pause | Shorter pause, same shape | Same or higher, spread across cores |
| Concurrent | Runs GC work on helper threads while JavaScript keeps running | Near zero for that phase | Higher (barriers, coordination) |
None of these techniques removes work. They move it in time (incremental), spread it across cores (parallel), or take it off the main thread (concurrent). You pay for this with extra CPU and some bookkeeping overhead, and in return you get lower latency.
Incremental Marking
Incremental marking breaks the marking phase into small slices, often a few milliseconds each. Between slices, JavaScript runs normally. The difficulty is that your code can change the object graph between two slices. If the collector has already finished scanning an object and your code then stores a new reference inside it, the collector could miss the newly referenced object and free memory that is still in use.
Tri-color marking
To track progress across slices, collectors use tri-color marking. Each object is in one of three states:
- White: not yet discovered. At the end of marking, white objects are garbage.
- Grey: discovered as reachable, but its outgoing references have not been scanned yet.
- Black: reachable, and all its references have been scanned.
Marking starts by turning the roots grey. Each step takes a grey object, turns the objects it references grey, and turns the object itself black. Marking is done when no grey objects remain.
The write barrier
The rule that keeps marking correct is the tri-color invariant: a black object must never point to a white object. Scanning will never revisit a black object, so a white object referenced only from a black one would be freed by mistake.
To enforce this rule, the engine inserts a write barrier, a short piece of code that runs on every pointer write while marking is active. When your code executes something like parent.child = obj, the barrier checks whether parent is black and obj is white. If so, it marks obj grey so the collector will scan it. The engine emits this check inside the JIT-compiled code, so you never write it yourself. It does make each property write slightly more expensive while a marking cycle is running.
Parallel Collection
Parallel collection keeps the pause but shortens it by doing the work on several threads at once. The main thread and a set of helper threads all work on the same heap while JavaScript is stopped.
V8's young-generation collector, the Scavenger, is parallel. During a minor GC, several threads copy surviving objects out of the nursery at the same time. They split the roots and the remembered set between them, and they use atomic operations so two threads never copy the same object. Parallel work also appears in the old generation, for example during compaction, when live objects are moved to reduce fragmentation and the pointers to them are updated.
Parallelism is the simplest of the three techniques because JavaScript is not running and the object graph cannot change. Its limit is the number of available cores. On a machine or container with one CPU, a parallel phase gains nothing.
Concurrent Collection
Concurrent collection runs GC work on helper threads while JavaScript keeps executing on the main thread. V8 does most of its old-generation marking this way, and it sweeps concurrently as well.
Concurrent marking has the same graph-mutation problem as incremental marking, and the same write barrier solves it. It also has an extra problem: two threads touch the same object at the same moment, so the barrier and the marking bits must use atomic memory operations.
A major GC in V8 roughly follows this sequence:
- The heap passes a growth threshold, so the engine starts marking.
- Helper threads mark concurrently while JavaScript runs. The main thread may also do small incremental marking steps when it allocates.
- A short stop-the-world finalization pause re-scans roots and any remaining grey objects, then completes marking.
- Sweeping runs concurrently. Compaction of selected pages runs in parallel during the pause.
Idle-time scheduling
Chrome adds one more trick. The renderer knows when a frame has been produced early and the main thread has spare time before the next one. V8 can use these idle periods to run incremental marking steps or finalization, so GC work lands in time that would otherwise go unused. Node.js has no frame deadline, so this scheduling matters mainly in browsers.
Observing GC Pauses
You can watch these phases yourself. Node.js reports GC events through perf_hooks. The script below allocates many short-lived objects, keeps some of them so they get promoted to the old generation, and prints each GC event with its kind and duration.
const { PerformanceObserver, constants } = require("node:perf_hooks");
const kinds = {
[constants.NODE_PERFORMANCE_GC_MINOR]: "minor",
[constants.NODE_PERFORMANCE_GC_MAJOR]: "major",
[constants.NODE_PERFORMANCE_GC_INCREMENTAL]: "incremental",
[constants.NODE_PERFORMANCE_GC_WEAKCB]: "weakcb",
};
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const kind = kinds[entry.detail.kind] ?? "other";
console.log(`${kind.padEnd(11)} ${entry.duration.toFixed(2)} ms`);
}
});
observer.observe({ entryTypes: ["gc"] });
const kept = [];
for (let i = 0; i < 300; i++) {
const batch = [];
for (let j = 0; j < 10_000; j++) {
batch.push({ i, j, label: "item-" + j });
}
if (i % 5 === 0) kept.push(batch); // retained, so it ends up in old space
}
setTimeout(() => {
observer.disconnect();
console.log(`kept ${kept.length} batches`);
}, 200);Save it as gc-events.js and run node gc-events.js. Most lines will be minor, often around 1 ms or less, with a few major or incremental entries. The reported duration is roughly the main-thread time of each event. Concurrent marking on helper threads does not appear in it, which is the point.
For more detail, V8 prints a line per collection when you start Node.js with a trace flag:
# Print one line per GC with sizes and pause times
node --trace-gc gc-events.js
# Compare against a run with helper threads disabled (V8 flag)
node --single-threaded-gc --trace-gc gc-events.js--trace-gc lines show Scavenge for minor GCs and Mark-Compact for major GCs. A Mark-Compact line often notes how many incremental steps ran since marking started, which shows how much of the marking happened before the final pause. In the browser, the DevTools Performance panel shows Minor GC and Major GC blocks on the main-thread track, and their widths show the real pause lengths.
Gotchas and Failure Modes
- Allocation outpacing marking. If your code allocates faster than concurrent marking can keep up, the heap reaches its limit before marking finishes. V8 then has to complete the remaining work in a longer pause. The usual cause is a high allocation rate. The next chapter covers how to lower it.
- Large live heaps still cost time. Finalization re-scans roots and leftover grey objects, and compaction moves live data. A heap with millions of live objects has longer final pauses even with all three techniques in use.
- Throughput trade-off. Write barriers and thread coordination add CPU time overall. Batch jobs that only care about total runtime gain less from these techniques than interactive apps do.
- Short pauses add up. Many 1 ms minor GCs per frame still eat into the frame budget. Short individual pauses do not mean GC is cheap for your workload.
- You cannot control scheduling from JavaScript. There is no standard API to pick when GC runs. Node's
--expose-gcflag exposesglobal.gc()for testing, but calling it in production forces a full stop-the-world collection and makes pauses worse.
Deciding What to Do
You rarely tune these collector modes directly. They are on by default and work well. Use this chapter's model to interpret what you measure:
- Long
Mark-Compactpauses with a large heap: reduce what stays alive (leaks, oversized caches). - Frequent
Scavengeevents: reduce the allocation rate in hot code. - Pauses that get worse only in production: compare CPU limits and core counts with your development machine.
Exercise
During incremental marking, an object config has already been marked black. Your code then runs config.handler = newObject, where newObject was just created and is still white. What would go wrong without a write barrier, and what does the barrier do?
Show answer
Black objects are never re-scanned, so without a barrier the collector would never discover newObject through config. If nothing else references it, it would stay white and be freed while still in use. The write barrier sees a white object being stored into a black one and marks newObject grey, so the collector scans it before marking finishes.
Exercise
Explain the difference between parallel and concurrent garbage collection in one or two sentences each, and say which one V8's Scavenger uses.
Show answer
Parallel GC uses several threads at the same time while JavaScript is stopped, which makes a pause shorter. Concurrent GC runs on helper threads while JavaScript keeps executing, which removes that work from the main-thread pause. V8's Scavenger (young generation) is parallel.
Exercise
A Node.js service shows occasional 80 ms Mark-Compact pauses in --trace-gc output. It runs in a container with a 1-CPU limit and allocates heavily per request. Name two likely contributing causes based on this chapter.
Show answer
First, with only one CPU, concurrent marking and sweeping threads compete with JavaScript, so less GC work happens off the main thread. Second, a high allocation rate can fill the heap before concurrent marking finishes, which forces V8 to complete the work in a longer final pause. A large live heap would also lengthen finalization and compaction.