The pattern is familiar. Memory climbs slowly for a day or three, then a pod restarts with OOMKilled, or the process dies with FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory. The restart brings memory back down, so the graph looks like a saw with very long teeth. And it never happens on your machine, because nothing on your machine runs for three days under real traffic.
Restarts hide a leak, they don't fix it. Here's how I'd go from "memory keeps growing" to the line of code that holds on to it.
First: is it actually a leak?
Node's memory always moves. V8 allocates, collects, allocates again, so a healthy service draws a sawtooth. A leak is when the bottom of the sawtooth keeps rising: what survives each major garbage collection grows, while traffic stays flat.
Three numbers from process.memoryUsage() tell most of the story:
-
heapUsed: memory held by live JavaScript objects. A leak in your code shows up here. -
heapTotal: what V8 has reserved for the heap. It followsheapUsedup and comes down slowly. -
rss: everything the process holds, heap included. If RSS climbs while the heap stays flat, look outside JavaScript objects: Buffers (externalandarrayBuffersin the same call), streams nobody consumes, native modules.
process.memoryUsage() won't tell you which part of the heap is growing. v8.getHeapSpaceStatistics() will. A leak of long-lived objects shows up in old_space; a leak of big strings or arrays in large_object_space; and a new_space that's busy but flat is just allocation churn. v8.getHeapStatistics().heap_size_limit tells you the ceiling V8 is actually running with, which is the number to compare against the container limit below.
Two shapes that look like leaks but aren't:
- Memory that tracks traffic and comes back down at night is load, not a leak.
- A step up right after a deploy is a regression to bisect, whether or not it keeps growing afterwards.
One setting to get right before anything else: the heap limit. If your container's memory limit is lower than what V8 thinks it may use, the kernel kills the process from outside (OOMKilled, exit code 137) and you get no error, no stack and no chance to write a snapshot. Set --max-old-space-size explicitly, comfortably below the container limit, leaving room for everything outside the heap. Then V8 hits its own limit first, which is the version of the crash you can learn from.
Where NestJS apps usually leak
Most leaks in Nest apps come down to one fact: providers are singletons by default. A service lives as long as the application does, so anything it holds on to lives that long too.
A singleton that remembers things. A Map of users seen, a "recently processed ids" set, a list of failed payloads to retry later. Each entry is small, and nothing ever removes one:
@Injectable()
export class RatesService {
private readonly cache = new Map<string, Rate>(); // grows with every new key, forever
async rateFor(currency: string, day: string) {
const key = `${currency}:${day}`;
if (!this.cache.has(key)) {
this.cache.set(key, await this.fetchRate(currency, day));
}
return this.cache.get(key);
}
}
Give it a size limit (an LRU), a TTL, or move it to Redis. A day in the key is a classic: the set of possible keys never stops growing.
A DataLoader shared across requests. DataLoader caches every key it has loaded for the lifetime of the instance. Its own README recommends a new one per request: a long-lived loader can consume too much memory, and one cache shared across many users can be dangerous. Put it in a singleton provider and you get both:
@Injectable() // one instance for the whole app...
export class AuthorsLoader {
readonly byId = new DataLoader((ids: readonly string[]) =>
this.authors.findByIds(ids), // ...so its cache keeps every author ever loaded
);
constructor(private readonly authors: AuthorsService) {}
}
Create loaders per request instead, in your GraphQL context factory or with @Injectable({ scope: Scope.REQUEST }). Request scope bubbles up, so every resolver that injects the loader becomes request-scoped too. That's usually fine for loaders, but it's worth knowing, and it leads straight to the next one.
Request-scoped instances that never get collected. This one is common, and it's easy to miss because request scope looks like it should clean up after itself. Nest keeps request-scoped instances in a WeakMap keyed by the request's ContextId, which it attaches to the request object. When the request finishes and nothing else points at it, the request, its ContextId and every instance created for it are collected together. The leak starts when something long-lived keeps a reference to one of those instances, and it usually happens in the constructor:
@Injectable({ scope: Scope.REQUEST })
export class AuditContext {
private readonly entries: AuditEntry[] = [];
constructor(
@Inject(REQUEST) private readonly request: Request,
events: EventEmitter2, // a singleton
) {
// The singleton emitter now holds this closure, the closure holds `this`,
// and `this` holds the request: headers, body, user. Every request adds one.
events.on('order.created', (order) => this.entries.push(toEntry(order)));
}
}
Nothing ever removes that listener. Request-scoped providers don't get a per-request teardown hook: Nest calls onModuleDestroy and the other lifecycle hooks only on static (singleton) instances, and only when the application shuts down. So anything a request-scoped instance attaches to a longer-lived object stays attached: a listener on an app-wide emitter, a subscription to a Subject in a singleton, a callback registered with a client or a pool, a setTimeout that captures this, or simply registry.push(this) in a singleton that keeps track of "active" contexts. One reference is enough, and it pins the whole request with it.
The fix is to keep the direction of references one-way: request-scoped code may use singletons, but singletons must not end up holding request-scoped instances. Move the listener into a singleton and pass it what it needs per event. If something genuinely has to be per request, release it when the response finishes, for example with request.res?.once('close', () => events.off('order.created', handler)) on Express.
In a heap snapshot this leak has a recognisable signature. The count of your request-scoped class (and of IncomingMessage) should stay close to the number of requests in flight; in the comparison view it grows by roughly the number of requests served between the two snapshots instead. Its retainers end in the long-lived object: the emitter's _events, a Subject's observers, the singleton's array.
Durable providers are the deliberate exception to "collected with the request". With a ContextIdStrategy that returns one durable context per tenant, Nest keeps one set of instances per tenant for as long as your strategy keeps that tenant's ContextId, which is the point, as long as the set of tenants is bounded. Key it by something unbounded (a user id, a header a client controls) and you've built the Map from the first example out of DI. Instances you create yourself with ModuleRef.create() are outside the container's bookkeeping entirely: they live as long as you hold them.
Listeners added per request. this.events.on('order.paid', handler) inside a request handler, on an emitter that outlives the request, adds a listener every time and keeps every closure. Node warns you with MaxListenersExceededWarning once one event has more than 10 listeners. Treat that warning as a leak report, not as noise to silence with setMaxListeners.
Subscriptions that never end. The RxJS version of the same thing: subscribing to a long-lived Subject or interval in a service or interceptor without take, takeUntil or an unsubscribe. Each subscription keeps its closure, and whatever the closure captured.
Requests captured by something long-lived. The same mistake without request scope: pushing req into a singleton's array "to handle later" keeps the whole request alive, headers, body, user. Store the few fields you need instead.
Caches without limits. An in-memory cache with no TTL and no size limit is a Map with extra steps.
Timers nobody clears. A setInterval started in a provider and never cleared in onModuleDestroy. In production it's usually one timer and harmless, but in tests and hot reloads they pile up.
Proving it with heap snapshots
Guessing from code gets you a long way. A heap snapshot tells you for sure: which objects are piling up, and what keeps them alive.
Node can write one on a signal. Start the process with the flag:
node --heapsnapshot-signal=SIGUSR2 --max-old-space-size=1536 dist/main.js
and send the signal when memory is high:
kill -USR2 <pid>
The snapshot lands in the process's working directory, named like Heap.20261020.143012.4213.0.001.heapsnapshot. In Kubernetes, kubectl cp it out of the pod.
To catch the moment before the crash, there's --heapsnapshot-near-heap-limit=2: Node writes up to two snapshots as the heap approaches its limit. It stopped being experimental in Node.js 22.22.1, 24.13.1 and 25.4.0.
Both come with a cost you should plan for. Node's docs are explicit about it: generating a snapshot blocks the event loop for a time that depends on the heap size, and needs memory about twice the size of the heap. On a process already near its limit, that can get it killed. So take snapshots from one replica with headroom, ideally drained of traffic first, and expect a pause.
There's a cheaper option for the "what's allocating" half of the question. --heap-prof runs V8's sampling heap profiler for the life of the process and writes a .heapprofile when it exits, which DevTools opens as an allocation profile grouped by function. It samples instead of walking the whole heap, so it costs little, but it only writes on a clean exit, which makes it a fit for one replica you drain and stop on purpose, not for catching a crash. For a snapshot on demand without a signal, v8.writeHeapSnapshot() returns the file name it wrote; put it behind an admin-only endpoint if you do, since the snapshot contains everything in memory, secrets included.
Then compare:
- Take one snapshot after warm-up, and another after the heap has grown for a while (a third, later still, makes the pattern unmistakable).
- Open them in Chrome DevTools, in the Memory tab.
- Select the later snapshot and switch the view to Comparison against the earlier one. Sort by size delta.
- Pick the constructor that grew the most and read its Retainers. The chain usually ends at a field of one of your providers:
RatesService.cache,AuthorsLoader.byId.
If you can reproduce locally, it's the same procedure with node --inspect and DevTools attached, and a load generator (autocannon, k6) pointed at the endpoint you suspect. Which raises the question: which endpoint?
Finding the endpoint with NestJS Observe
This is where production telemetry earns its keep. A snapshot tells you what's retained. It doesn't tell you which request put it there, when it started, or whether every instance is affected.
NestJS Observe samples each process's RSS, heap total, heap used, garbage collection and event loop every 60 seconds by default (runtimeMetricsInterval), alongside the requests and jobs it traces. It's on every plan, Free included, and runtime metrics aren't billed as events.
The page opens on a verdict for one application: Coping, Strained or Under pressure, judged on four gauges, with a sentence naming the reading it rests on. For a leak, don't lean on the memory gauge. It's the process's RSS against the total memory the operating system reports, and inside a container that's usually the whole machine's memory, not the pod's limit, so a pod about to be OOMKilled can still read a few percent. The heap chart and its trend are the signal for this job.
Below it, the Memory chart draws RSS, heap total and heap used together, and they nest, so the gaps between them mean something. Heap growing inside a flat RSS is ordinary. RSS growing away from the heap points at buffers or native memory.
You don't have to spot the trend yourself. When the mean heap in the last third of the window is 30% or more above the first third, the page shows a "Heap usage keeps climbing" notice. It compares thirds so that a normal sawtooth can't trigger it, and it doesn't depend on knowing the limit at all. And when the climb tracks one request or job, its calls rising and falling with the heap bucket by bucket, a card at the top of the Memory band names that operation. That's the endpoint to load-test locally while you take snapshots.
Then narrow it down:
- Instances. When an application runs on several pods, there's a card per instance with its CPU, memory and loop lag, and a line under the verdict says whether they read alike or which one stands apart. Click a card to chart that pod. One pod climbing while the others stay flat says the leak depends on traffic that pod gets: one tenant, a sticky session, a consumer holding every partition.
- Releases. If the climb starts at a deploy, the diff between those two releases is where to look. A release's page lists, under "What changed in the code", the methods, queries and outbound calls whose behaviour moved across the deploy, which narrows that diff to the code that actually runs differently.
- What ran here? Click a point on the Memory chart where the heap stepped up, and a drawer lists the requests and jobs that ran unusually at that moment. They're ranked by how far each one's rate or duration strayed from its own baseline, so a rarely called export endpoint that suddenly ran 12 times stands out over your busiest route.
The GC charts back the story up. As a leaking heap fills, major collections get more frequent and garbage collection takes a growing share of the time.
Once you have a suspect, measure it directly instead of inferring it from the heap. A custom gauge on the field you think is growing puts its size on a chart next to the heap:
@Injectable()
export class RatesService {
private readonly cache = new Map<string, Rate>();
constructor(private readonly tracer: TracerService) {}
@Interval(60_000)
reportCacheSize() {
this.tracer.gauge('rates.cache.size').setValue(this.cache.size);
}
}
If that line climbs in step with the heap, you've found it. If it's flat, you've ruled it out in an afternoon instead of a snapshot session. Custom metrics aren't tied to a trace, so they report from a timer like this one, and they can be alerted on like any built-in metric.
Once you've fixed it, keep watching. Runtime alert rules (on Pro and up) can watch memory usage per application, and anomaly mode ("unlike its own recent baseline") is often a better fit than a fixed threshold, since a normal heap size for one service is a leak for another.
Before the next one
- Set
--max-old-space-sizebelow the container's memory limit, so V8 fails before the kernel does. - Run at least one replica with
--heapsnapshot-near-heap-limitand a writable directory with room for a snapshot. - Watch the heap's trend, not only its level. A threshold tells you minutes before the crash; a trend tells you days before.
- Look at singletons first. Most leaks are a field on a provider that only ever grows.
- Check that no singleton ends up holding a request-scoped instance. If your request-scoped class's instance count in a heap snapshot is far above the number of requests in flight, something long-lived is keeping them.
- Don't treat restarts as the fix. They reset the clock and hide the trend.
If you want to see what the Profiler shows before you install anything, the live demo needs no signup.


Top comments (0)