Repository navigation
buffer: implement pooling mechanism for Buffer.allocUnsafe #30683
Description
The problem
At the moment Buffer.allocUnsafe uses a pre-allocated internal Buffer which is then sliced for newly allocated buffers, when possible. The size of the pool may be configured by setting Buffer.poolSize property (8KB by default). Once the current internal buffer fills up, a new one is allocated by the pool.
Here is the related fragment of the official documentation:
The Buffer module pre-allocates an internal Buffer instance of size Buffer.poolSize that is used as a pool for the fast allocation of new Buffer instances created using Buffer.allocUnsafe() and the deprecated new Buffer(size) constructor only when size is less than or equal to Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).
While this mechanism certainly improves performance, it doesn't implement actual pooling, i.e. reclamation and reuse of buffers. Thus it doesn't decrease allocation rate in scenarios when Buffer.allocUnsafe is on the hot path (this is a common situation for network client libraries, e.g. DB drivers).
This issue is aimed to discuss the value of such pooling mechanism and provide a good starting point for initial design feedback.
There are two main options for pooling in Node.js:
- Provide an API for manual reference counting. This approach is unsafe and requires a lot of discipline from uses, so it doesn't sound like a good candidate.
- Integrate with GC for buffer reclamation. This one is more complicated and requires integration with GC.
It appears that option 2 is feasible with experimental APIs (FinalizationGroup and, maybe, WeakRefs).
The solution
The implementation idea was described by @addaleax (see #30611 (comment))
FinalizationGroup API could be enough to implement a pool that would reuse internal buffers once all slices pointing at them were GCed. When the pool uses an active internal buffer (let's call it a source buffer) to create slices, it could register those slices (as "the object whose lifetime we're concerned with") with their source buffer (as "holdings") in a FinalizationGroup. Once a finalizer function is called and it reports that all slices were GCed (it could be based on a simple counter), the pool could reclaim the corresponding source buffer and reuse it.
There are some concerns with this approach.
First, this pooling mechanism may potentially lead to performance degradation under certain conditions. For large source buffers the cost of bookkeeping of all slices in the FinalizationGroup may be too high. For small source buffers (especially with 8KB source buffers which is the default in the standard API's global pool) it's probably not worth it at all. This could be mitigated by using a hybrid approach: use current mechanism in case for small buffer allocation as the fallback. So, some PoC experiments and benchmarking have to be done.
Another concern is that it's an experimental API, so I'm not sure if FinalizationGroups are available internally without --harmony-weak-refs flag (or planned to become available), like it's done for internal WeakReference API.
Proposed plan:
- Gather initial feedback
- Implement a PoC and benchmark it
- Discuss next steps (potentially, support in node core)
Alternatives
Such pool could be certainly implemented as an npm module. However, support in node core could bring performance improvements to a much broader audience.
Activity
addaleax commentedon Nov 27, 2019
Don’t you mean the other way around? The slices are what should be tracked, not the source buffers, right?
I don’t know what the V8 team’s plan on this is but I guess whatever we implement could be behind that flag for now? Weakrefs are a stage 3 proposal, so I think we can be relatively certain that they’re going to be standardized and implemented without requiring flags in the future.
lin7sh commentedon Nov 27, 2019
WeakReference implementation in v8 seems ready, it only blocked by chromium integration https://bugs.chromium.org/p/v8/issues/detail?id=8179
puzpuzpuz commentedon Nov 27, 2019
Sure. We need to track slices as source buffer's "holdings".
FinalizationGroupAPI on its own may be sufficient to achieve this.Thanks for noticing this incorrectness. I'll update the description.
Yeah, nothing prevents activating this mechanism under the flag.
puzpuzpuz commentedon Nov 28, 2019
As a follow-up, I have created a PoC repo: https://github.com/puzpuzpuz/nbufpool
It's in a very early draft stage at the moment. But at least the pool seems to be working (not covered with tests yet).
I have a couple of questions so far:
--harmony-weak-refs, I had to add--noincremental-markingflag. Otherwise node crashes:I see that all tests for
FinalizationGroupin node are assumed to be run with--noincremental-marking. Is it a known issue?Buffer.allocUnsafe? I'd like to understand their scenario, especially allocation rate that is sufficient for performance testing. Benchmark in the PoC repo is very primitive and I'd like to choose the right direction for improving it.addaleax commentedon Nov 28, 2019
Yes, #30616 should address that :)
I think benchmark/buffers/buffer-creation.js would be the main one?
puzpuzpuz commentedon Nov 28, 2019
That's great. I'll be watching this PR.
Thanks. This one is even more primitive than mine, but it's still valuable as I can look at buf sizes and number of ops.
addaleax commentedon Nov 29, 2019
@puzpuzpuz I’ve merged #30616, that crash should go away now :)
puzpuzpuz commentedon Nov 29, 2019
@addaleax I tested both v13 and v14 nightly builds. v14 works fine, but v13 still crashes. I guess that the commit just wasn't included into the latest nightly and I should wait for one more day, right?
addaleax commentedon Nov 29, 2019
@puzpuzpuz We don’t always update release branches regularly, usually only when preparing a release. I’ve pushed that commit to v13.x-staging now, though.
puzpuzpuz commentedon Nov 29, 2019
@addaleax Thanks for the clarification and for the push. I'm going to use v13 nightly for further experiments.
puzpuzpuz commentedon Dec 1, 2019
I improved the benchmark and spent some time on experiments.
Here are results for the most simple pool implementation (no constraints on pool size or throttling):
Considerations:
Buffer.allocUnsafe. So, the pool has some potential.Buffer.allocUnsafe) does a better job, then FG-based buffer reclamation. FG has to do bookkeeping for tens thousands of slices and its overhead overweights the value of buffer reusage. I also profiled these scenarios and FG calls are the most "heavy" calls in the profiler report.Buffer.allocUnsafeSlow) and reusage of buffers from the pool. Say, in the 512KB scenario it's 10496 for allocations vs. 251648 for reusages for the pool (~1/25).Further plans:
setImmediatecallbacks in a loop within each iteration and keeping strong references for allocated buffers until the next iteration. This should be close enough to what happens in network apps.Any feedback is highly welcome.
puzpuzpuz commentedon Dec 1, 2019
A small update.
I just realized that there is a way to significantly reduce amount of FG bookkeeping by introducing another level of indirection. :)
Going to implement it and measure the impact.
puzpuzpuz commentedon Dec 2, 2019
@addaleax
As planned, I have reduced amount of FG bookkeeping and it improved the performance. I also implemented primitive shrinking of the pooled buffers by storing pool's contents in a WeakRef.
However, there is one issue that blocks me. It looks like FG stores strong references to all "holdings" until forever. Even when the finalizer callback was triggered and "holdings" of GCed objects were iterated, references to them are kept internally in FG (or at least, that's how it looks like for the outside).
As I was trying to use source buffers as "holdings" in
FinalizationGroup.registercall (and an intermediate slice as the key object, i.e. the first argument), it becomes really critical: the off-heap memory keeps growing during the benchmark and it's never freed.You may see it if you try to run
node --harmony-weak-refs benchmark/benchmark.jsin the experimental library. On my machine memory consumption of the Node.js process goes up to almost 22GB.I tried to introduce an intermediate map with
<int-seq-num, source-buffer>pairs and it solved the memory problem, but that approach is obviously slower.Does it sound like expected behavior of FG API or a bug to you? If that's expected, does it mean that the API can only accept on-heap objects and primitives?
addaleax commentedon Dec 8, 2019
@puzpuzpuz I’m not sure – it looks like a bug in V8 to me, yes. Which I guess is fair for a feature behind an experimental flag.
I’m seeing the behaviour with the latest V8 master too – can you maybe try to break this down into a smaller reproduction?
puzpuzpuz commentedon Dec 8, 2019
@addaleax
I wasn't expecting feature under experimental flag to be rock solid. I'm going to write a simple reproducer and create a separate GH issue.
puzpuzpuz commentedon Dec 8, 2019
Created #30853 to track the memory consumption issue.
dball commentedon Jun 14, 2024
I find myself wanting this very feature and am curious if this idea ran into technical issues, and, indeed, what folk are doing instead?
github-actions commentedon Jun 27, 2026
This issue has been marked as stale due to 210 days of inactivity.
It will be automatically closed in 30 days if no further activity occurs. If this is still relevant, please leave a comment or update it to keep it open.
github-actions commentedon Jul 28, 2026
This issue has been automatically closed after 30 days of inactivity following its stale status (no activity for a total of 120 days).
If this is still relevant, feel free to reopen it or leave a comment with additional details so we can continue the discussion.