AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Default "Use Cache" Handler Pins Buffer Pool Slabs Causing Memory To Exceed CacheMaxMemorySize By Up To 22X On Node 26

The default `use cache` handler stores `streamToBuffer` results that may be small slices of a shared Buffer pool slab. Long-lived cache entries therefore retain whole pool slabs (64 KiB on Node 26) while the LRU only counts the slice's bytes, causing actual memory usage to exceed `cacheMaxMemorySize` by up to 22x.

highConfidence 95%Next.jsAffected V16.4.0

Origin Analysis

In `dist/server/lib/cache-handlers/default.js`, `set()` calls `streamToBuffer(entry.value)` and stores the returned Buffer. When total bytes are below `Buffer.poolSize >>> 1`, `Buffer.concat` returns a slice of a shared pool slab; retaining this slice keeps the entire slab alive, so the LRU's `value.byteLength` accounting vastly underestimates real retained memory.
1. Run Node.js 26.7.0. 2. Build and start Next.js with `--expose-gc` using the reproduction repo. 3. Generate 10,000 cache entries of ~1 KB via `/item/<n>` routes. 4. Force GC and read `/api/memory`; compare ArrayBuffers after GC: 221 MB with 64 KiB pool vs 42 MB with 8 KiB pool vs 10 MB after applying unpooled copy.

Fixing Code Block

Edge Case Audit

The unconditional copy adds an extra allocation and copy for every entry; for entries larger than half the Buffer pool size, `streamToBuffer` already returns a non-pooled exact-size buffer, so this adds avoidable peak memory and CPU overhead. In high-throughput cache writes, prefer conditionally copying only when `pooled.byteLength < pooled.buffer.byteLength` (or checking `pooled.buffer.byteLength !== pooled.byteLength`) to limit overhead. Rollback: keep the original `const value = await streamToBuffer(entry.value);` line and remove the copy; affected deployments can temporarily set `Buffer.poolSize = 8192` to reduce the gap. Also note the fix must remain in the transpiled `dist` output used by production builds; ensure source changes are rebuilt or patched in both source and dist.

Ecosystem Topology