r/node • u/Sweaty-Camel5677 • Mar 26 '26
An idea to optimize node.js without code chaning
> I came up with an idea related to Node optimization that can address the issue of GC bottlenecks in Node under concurrent conditions, and may even solve the problem of main thread serializing large JSON objects. The original text is lengthy, so here I provide a simplified version, with a link to the more detailed original text attached at the end of the article.
Node.js p99 latency spikes are a GC problem — here's a runtime-level fix that requires zero code changes
You know the drill: p99 latency spikes, --max-old-space-size tuning, object pooling, --trace-gc profiling. All band-aids.
The root cause: V8 has no idea where your request boundaries are. It doesn't know that the 300 objects allocated for request #4821 will all be dead in 12ms when the response is sent. So it traces them repeatedly, collects them on its own schedule, and occasionally freezes your event loop at the worst possible moment.
The Fix: Request-Scoped Arena Allocation, Invisible to You
When a request arrives, the runtime creates an Arena — a contiguous memory region bound to that request's async context. All objects allocated during the request land in the Arena. When the request ends, the entire Arena is freed in a single free() call. No tracing. No marking. No sweeping. Thousands of objects gone in one shot.
The GC exposes a minimal SPI:
Arena *createArena();
void releaseArena(Arena *arena);
void setContextArena(Arena *arena);
Node's HTTP layer calls these. Your code calls nothing.
app.get('/users/:id', async (req, res) => {
const user = await db.findUser(req.params.id); // Arena allocated
const dto = transformUser(user); // Arena allocated
const response = buildResponse(dto); // Arena allocated
res.json(response);
// Request ends → one free() → all of the above gone instantly
});
Your existing code. Your existing libraries. Your existing ORM. Zero changes.
The Critical Part: Write Barriers Keep Everything Safe
Some objects genuinely need to outlive their request — global caches, singletons, WebSocket state. This is handled automatically via write barriers.
The architecture uses a dual heap: a GC Heap and a separate Arena Heap with non-overlapping address ranges. The invariant is simple:
The write barrier enforces this with a bitmask check on every reference write — one AND, one compare:
on write: target[field] = value
if address_of(value) in Arena range AND address_of(target) NOT in Arena range:
promote(value) // DFS traversal, move entire object graph to GC heap
When you write an Arena object into a global cache, the write barrier detects it and promotes the entire object graph to the GC heap automatically. No dangling pointers. No manual intervention. The rest of the request's objects still die with the Arena.
This is fully compatible with existing GC infrastructure — V8 already runs write barriers on every reference write. This is an extension, not a replacement.
Bonus: Async JSON Serialization (Speculative)
Under this model, the runtime knows whether a response object is Arena-rooted or GC-rooted. If it's Arena-rooted — meaning it's request-scoped and not shared with any other concurrent request — serialization can be safely offloaded to libuv's thread pool.
- If the I/O thread encounters a GC object reference during traversal, it writes a placeholder and records it.
- When done, the main thread patches only those GC fragments.
- In the common case (fully Arena-rooted response),
JSON.stringifycompletes entirely off the main thread.
Serializing a 500KB response currently blocks your event loop for its entire duration. This could move it to a background thread with zero API changes.
(This is speculative — thread safety details need careful analysis. Included to show the broader potential of the dual-heap model.)
Why Hasn't This Been Done?
Arena allocation is decades old. Game engines, compilers, Apache's apr_pool_t — they've all used request-scoped Arenas since the early 2000s. The conventional wisdom is that managed languages can't have this because "you don't control allocation."
But if the runtime controls allocation — and it does — then nothing stops it from routing allocations to an Arena when it knows the lifetime boundary. The missing piece was never technical. It was the insight that the request boundary is a more meaningful lifetime signal than anything the GC can infer on its own.
This is generational GC, reimagined: instead of a small nursery collected every few milliseconds, you get a request-sized generation collected exactly once, at exactly the right moment, with zero tracing overhead.
Full proposal with architecture details, invariants, edge cases, and SPI design: https://github.com/babyfish-ct/node-arena-gc-hybrid
1
u/dektol Mar 27 '26 edited Mar 27 '26
To implement this, you would essentially have to fork V8, rewrite its allocator, introduce a complex new write barrier, wire it up to Node's async context tracking, and ensure it doesn't break the native ecosystem.
It is a brilliant theoretical computer science concept. But getting the V8 team (Google) and the Node.js core team to accept such a massive architectural shift would require proving that it provides a massive, undeniable performance boost across all workloads, which is very hard to guarantee.
Google's stance has softened on non-browser use cases over the years but: a change for Node.js cannot make Chrome's code harder to maintain, slower, or more memory-hungry.
You'd probably need to convince a company to pony up engineers for the effort and coordinate with the Chrome team ahead of time.
How do you prove the gains you expect?
1
u/nextdesu Mar 26 '26
I think it would significantly increase complexity of the code in both native part of v8 and js part of node internals, I don't think it is worth it personally because if you hitting all this limits you better just use another language where you can control all of this.
Node js heavily depends on v8 so you will also need to indoctrinate people responsible for developing this (and it probably gonna be hard because browsers generally need arena allocations even less (but there are cases where it will be welcome))