Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 10 min read

The Bytes Under My Buffer Are Not Mine

Write Buffer.from('OK') and you get a two-byte thing. The two bytes are real, but an 8192-byte slab sits underneath them, carrying the data of whatever code wrote there before you. The moment you reach for the .buffer pr

Write Buffer.from('OK') and you get a two-byte thing. The two bytes are real, but an
8192-byte slab sits underneath them, carrying the data of whatever code wrote there
before you. The moment you reach for the .buffer property, your window stops being two
bytes wide.

My thesis: Node's Buffer pool is less a speed detail than a question of visibility
boundaries
. buf.length tells you what you asked for, buf.buffer.byteLength tells you
what is within reach. On this machine the gap came out as 2 bytes against 8192. You do not
need a scary-sounding call like allocUnsafe to see it either; Buffer.from('hello') is
enough.

Every number below was produced on 26 November 2026 on a single machine running
node v22.16.0 (arm64, darwin). The scripts appear in full; copy them and run them on
your own version, because as you will see at the end, some of these numbers changed in
Node 26.

Two Buffers on one slab

The scenario is a deliberate lab setup: one code path takes a Buffer from the pool and
writes an authorization header into it, and right afterwards an unrelated path creates a
small output buffer. Here is the whole script:


const secret = Buffer.from('Authorization: Bearer s3cr3t-token-42');
const out = Buffer.from('OK');

console.log('secret : %d bytes at byteOffset=%d', secret.length, secret.byteOffset);
console.log('out    : %d bytes at byteOffset=%d', out.length, out.byteOffset);
console.log('same ArrayBuffer : %s', out.buffer === secret.buffer);
console.log('out.buffer size  : %d bytes', out.buffer.byteLength);

const window = Buffer.from(out.buffer, 0, out.buffer.byteLength);
console.log('read %d bytes at offset %d: %j',
  secret.length, secret.byteOffset,
  window.subarray(secret.byteOffset, secret.byteOffset + secret.length).toString());

Its output:

secret : 37 bytes at byteOffset=8
out    : 2 bytes at byteOffset=48
same ArrayBuffer : true
out.buffer size  : 8192 bytes
read 37 bytes at offset 8: "Authorization: Bearer s3cr3t-token-42"

The two-byte out sits on the same ArrayBuffer as its 37-byte neighbour, and that
neighbour comes back letter for letter. Nothing here is a bug; Node behaves as documented.
What is wrong is the reading that treats .buffer as "my buffer".

Do the same with Buffer.alloc(2) and .buffer.byteLength is 2 with byteOffset 0. The
window is exactly as wide as your buffer. An unpooled allocation costs more but shows its
boundaries as they are.

What the pool is: from the v22.16.0 source

You have to read the source of the version you measured, because this file changed over
recent months. In Node
v22.16.0's lib/buffer.js,
the pool is built by three small functions. First the slab is created:

function createPool() {
  poolSize = Buffer.poolSize;
  allocBuffer = createUnsafeBuffer(poolSize);
  allocPool = allocBuffer.buffer;
  markAsUntransferable(allocPool);
  poolOffset = 0;
}

Then every small allocation is handed out as a slice of that slab:

function allocate(size) {
  if (size <= 0) {
    return new FastBuffer();
  }
  if (size < (Buffer.poolSize >>> 1)) {
    if (size > (poolSize - poolOffset))
      createPool();
    const b = new FastBuffer(allocPool, poolOffset, size);
    poolOffset += size;
    alignPool();
    return b;
  }
  return createUnsafeBuffer(size);
}

The new FastBuffer(allocPool, poolOffset, size) line summarises the whole article: the
Buffer you get back is a view over the shared allocPool. It has no memory of its
own, just an offset and a length. alignPool() rounds the offset up to a multiple of
eight. Three back-to-back allocUnsafe(100) calls landed at offsets 8, 112 and 216, so
the step is always 104. Requests of 97 and 101 bytes showed the same step, meaning all
three occupy 104 bytes of pool.

Diagram

One caveat: byteOffset values depend on what the process allocated earlier. Even the
number of console.log lines in your script eats into the slab, so 8 and 48 may well
differ for you. The meaningful column is not the offset, it is .buffer.byteLength.

You do not need allocUnsafe to land in the pool

Most people know allocUnsafe demands care. That everyday calls descend onto the same
slab gets discussed less:

const probe = Buffer.allocUnsafe(8);
const row = (name, buf) => console.log(
  name.padEnd(30) + 'pooled=' + String(buf.buffer === probe.buffer).padEnd(7) +
  '.buffer.byteLength=' + buf.buffer.byteLength);
Buffer.allocUnsafe(100)       pooled=true   .buffer.byteLength=8192
Buffer.alloc(100)             pooled=false  .buffer.byteLength=100
Buffer.allocUnsafeSlow(100)   pooled=false  .buffer.byteLength=100
Buffer.from('hello world')    pooled=true   .buffer.byteLength=8192
Buffer.from([1,2,3])          pooled=true   .buffer.byteLength=8192
Buffer.concat([ab,cd])        pooled=true   .buffer.byteLength=8192
fs.readFileSync(d2-apis.mjs)  pooled=true   .buffer.byteLength=8192
crypto.randomBytes(16)        pooled=false  .buffer.byteLength=16
crypto.randomBytes(4000)      pooled=false  .buffer.byteLength=4000

The Node 22 documentation lists the pooled calls: Buffer.allocUnsafe(),
Buffer.from(array), Buffer.from(string) and Buffer.concat(). The run confirms that
list. One row is missing from it: fs.readFileSync. Reading a small file returns a pooled
Buffer. I could not find a sentence in the Buffer documentation saying so; the behaviour
showed up only by running it.

The cryptographic side stays out of the pool, but reading that as "key material is
deliberately protected" would be wrong. randomBytes(4000) is well under the threshold
and still unpooled, so no size rule is at work here. Those buffers never pass through
allocate() at all; being unpooled follows from where they are constructed.

Where the threshold really is

The Node documentation writes the threshold two ways in the same section. The allocUnsafe
rule says "only when size is less than Buffer.poolSize >>> 1", while the alloc
comparison just below says "if size is less than or equal to half Buffer.poolSize".
One is less-than, the other less-than-or-equal.

Running each size in its own process gave this:

allocUnsafe(4094) .buffer.byteLength= 8192 byteOffset=    8 same_ArrayBuffer_as_probe=true
allocUnsafe(4095) .buffer.byteLength= 8192 byteOffset=    8 same_ArrayBuffer_as_probe=true
allocUnsafe(4096) .buffer.byteLength= 4096 byteOffset=    0 same_ArrayBuffer_as_probe=false
allocUnsafe(4097) .buffer.byteLength= 4097 byteOffset=    0 same_ArrayBuffer_as_probe=false
allocUnsafe(8192) .buffer.byteLength= 8192 byteOffset=    0 same_ArrayBuffer_as_probe=false

4095 comes from the pool, 4096 from its own allocation. The
if (size < (Buffer.poolSize >>> 1)) line in the source says the same. The correct
phrasing is less-than; the second sentence is wrong. To be fair to the documentation, the
allocUnsafeSlow section on the same page gives a concrete number β€” "allocations less
than Buffer.poolSize >>> 1 (4KiB when default poolSize is used)" β€” and it also lands on
less-than. Two of the three statements are right, so the page is not hopeless; it only
misleads someone working exactly at the boundary.

That last row corrects a piece of folklore too: an 8192-byte request looks pooled because
its byteLength is 8192. It is not; it has its own ArrayBuffer at offset zero.

My measuring tool gave the wrong answer twice

My first attempt tested "is it pooled?" as .buffer.byteLength === Buffer.poolSize. That
test answered wrongly for allocUnsafe(8192): the dedicated allocation also happens to be
8192 bytes, so it reported "pooled" when it was not.

My second attempt stored the first small buffer's ArrayBuffer and compared identity
against later ones. That one failed too, this time reporting "not pooled" for 4095. The
cause is these two lines inside allocate():

if (size > (poolSize - poolOffset))
  createPool();

When room runs out, Node opens a new pool. Part of the 8192-byte slab was already consumed
by earlier allocations, so the 4095-byte request overflowed it, a fresh slab opened, and
the comparison against my saved reference returned false. The buffer was pooled; my
reference had gone stale.

The third and correct rig: measure each size in its own process, allocate one more byte
immediately afterwards, and check whether the two share an ArrayBuffer.

const x = Buffer.allocUnsafe(n);
const probe = Buffer.allocUnsafe(1);
const pooled = x.buffer === probe.buffer;

The threshold table above comes from that rig. When you measure a mechanism that carries
state, your instrument is affected by that state too; the reference you assume is fixed
shifts mid-measurement.

Transfer is blocked, copying is not

The markAsUntransferable(allocPool) line inside createPool() marks the slab as
non-transferable. Measured:

pooled -> transfer FAILED: DOMException: Cannot transfer object of unsupported type.
alloc  -> transfer SUCCEEDED
structuredClone copy (no transfer): 8192 bytes

It is tempting to read that mark as a confidentiality measure, but that is not right.
Transferring the slab to another thread would invalidate every live Buffer on it, so
what is being prevented is corruption rather than disclosure. Copying stays open: hand the
.buffer of a pooled two-byte Buffer to structuredClone and an 8192-byte copy travels,
neighbours included.

Across threads the picture is better. Each worker opens its own pool:

main   : secret at byteOffset 8
worker : own pool byteLength=8192, indexOf("Bearer ") in worker pool = -1

The main thread's header is absent from the worker's slab, so this stays a single-thread
concern.

From v26.3.0 the slab is 65536 bytes

The freshness check earned its keep here. In the Node 22 documentation the
Buffer.poolSize default is 8192, and the v22.16.0 source line reads
Buffer.poolSize = 8 * 1024;. In the current documentation the default is 65536, and the
change-history row "Default raised from 8192 to 65536" points at v26.3.0. The line in the
main branch now reads Buffer.poolSize = 64 * 1024;.

The change covers v26.3.0 and later; v26.0 to v26.2 still ship 8192, and it was not
backported to v22. The effect runs two ways:

  • The threshold moves from 4096 to 32768. An 8 KiB buffer that used to get its own ArrayBuffer now falls into the pool.
  • The window visible through .buffer grows from 8 KiB to 64 KiB.

On top of that, every thread creates its own 64 KiB slab at startup, which in worker-heavy
or multi-process setups is a fixed cost eight times the old one.

What to do in practice

The pool is safe as long as you stay inside the bounds of buf.length. Trouble arrives on
lines that reach for .buffer, and those are usually well-meaning lines written in the
name of zero copy.

  • new Uint8Array(buf.buffer) or new DataView(buf.buffer) β€” without an offset and a length you wrap the whole slab. The right form is new Uint8Array(buf.buffer, buf.byteOffset, buf.length).
  • buf.subarray() and buf.slice() keep carrying the same ArrayBuffer, so the rule passes down to slices.
  • structuredClone(buf.buffer), or handing .buffer straight to a hash or encryption call β€” what you sign stops being what you think you sent.
  • Long-lived small slices keep the slab in memory. Holding 20,000 live two-byte Buffers pinned 20 separate slabs, so 163,840 bytes stay resident for 40,000 bytes requested: 4.1 times. In the worst case a single two-byte Buffer pins 8192 bytes.
  • buf.fill(0) clears only your own window. The slab is not wiped when a Buffer is dropped, so a secret written through Buffer.from(string) can stay on the slab for the life of the process.

The one general mitigation that works is turning the pool off:

default      : Buffer.from("OK").buffer.byteLength = 8192
poolSize = 0 : Buffer.from("OK").buffer.byteLength = 2
poolSize = 0 : allocUnsafe(100).buffer.byteLength  = 100

Buffer.poolSize = 0 disables pooling process-wide. The price is that every small buffer
becomes its own allocation, handing back the speed you gained.

The flag that comes to mind first does nothing here:

zero-fill-buffers active: true
out.buffer.byteLength   : 8192
neighbour still readable: "Authorization: Bearer s3cr3t-token-42"

--zero-fill-buffers only zeroes uninitialised memory. The neighbour's header is not
uninitialised garbage, it is properly written data, and the flag does not touch it.

My own rule ended up like this: any line where I write .buffer is incomplete unless
byteOffset and length appear beside it. For searching a codebase, grep -rn "\.buffer"
alone is very noisy; asserting buf.byteOffset !== 0 at runtime is a cheaper warning.

One dimension stayed unmeasured, and I will leave it open rather than guess: whether body
chunks from the net, http and stream layers are handed out from the pool was not
tested in this run. That is where real incidents would come from, and checking
chunk.byteOffset in your own code takes a minute.

Conclusion

This pool is a good example of what it costs to memorise an abstraction's boundary in the
wrong place. Buffer tells me "two bytes" and it is telling the truth. .buffer tells me
"the memory underneath" and that is true as well. The only false thing is the assumption
that both share the same boundary.

Node did what it could here: it stopped the slab being pulled out from under you,
separated the workers, and put the warning in the documentation. The rest comes down to
whether we remember to write byteOffset. The visibility of a shared resource is bounded
by the discipline of the code that uses it.

There are other places where Node declines to trust human memory about numbers and limits:
an earlier run showed
the exit code changing with the shape of the script.
A similar surprise about what memory counters do and do not show turned up in
the MADV_FREE measurement.
The shared lesson: reading the number is not enough, you have to read its scope too.

Official Sources

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.