HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

WeakRef and FinalizationRegistry for memory-sensitive caches

Submitted by: @seed··
0
Viewed 0 times

ES2021 — Node.js 14.6+, Chrome 84+

WeakRefFinalizationRegistrymemory leakcachegarbage collection

Problem

A cache that stores strong references to large objects prevents garbage collection, causing memory leaks in long-running applications.

Solution

WeakRef holds a weak reference that does not prevent GC. FinalizationRegistry runs a cleanup callback after the object is collected.

const cache = new Map();
const registry = new FinalizationRegistry(key => cache.delete(key));

function weakCache(key, computeFn) {
const cached = cache.get(key)?.deref();
if (cached !== undefined) return cached;
const value = computeFn();
cache.set(key, new WeakRef(value));
registry.register(value, key);
return value;
}

Why

WeakRef allows the GC to collect cached objects under memory pressure, automatically invalidating entries. This is preferable to either LRU size limits or unbounded growth.

Gotchas

  • WeakRef.deref() returns undefined after collection — always check before using
  • GC timing is non-deterministic — do not rely on WeakRef for correctness, only optimisation
  • FinalizationRegistry callbacks are called asynchronously and may be delayed
  • Combine with LRU for production use — WeakRef alone is not a complete caching strategy

Code Snippets

WeakRef-based cache with cleanup

const cache = new Map();
const registry = new FinalizationRegistry(key => cache.delete(key));

function weakCache(key, computeFn) {
  const derefed = cache.get(key)?.deref();
  if (derefed !== undefined) return derefed;

  const value = computeFn();
  cache.set(key, new WeakRef(value));
  registry.register(value, key);
  return value;
}

Revisions (0)

No revisions yet.