A Node.js container can be killed while its JavaScript heap looks perfectly healthy. The process consumes memory outside V8, and Kubernetes enforces a container memory boundary rather than a JavaScript object budget. Raising the limit may buy time, but it does not explain whether the next spike will kill the service again.

1. Establish what actually killed the process

Start with the terminated container state, not the current memory graph. A restarted pod may look healthy because its memory was reset. Kubernetes reports the last termination reason and exit code when that information is still available.

kubectl describe pod api-abc
kubectl logs api-abc -c api --previous
kubectl get pod api-abc -o jsonpath='{.status.containerStatuses[*].lastState.terminated}'

Substitute the actual pod, container and namespace. OOMKilled is evidence of an out-of-memory termination; exit code 137 by itself only indicates a SIGKILL-style exit and is not proof of a memory-limit breach. Check node events for memory pressure and eviction as well. A V8 fatal heap allocation error in previous logs is a different failure mode and may happen well below the container limit.

2. Measure the right layers

Node.js exposes resident set size (RSS), JavaScript heap usage, external memory and array-buffer allocations. RSS measures resident pages of the process, while heapUsed describes memory occupied by JavaScript objects. Array buffers include Node.js Buffer allocations and are already included in external memory; do not add those counters together. In a worker-thread application, RSS is process-wide but the other counters describe the current thread.

import { memoryUsage } from 'node:process';
import { getHeapStatistics } from 'node:v8';

export function memorySample() {
  const m = memoryUsage();
  return {
    rss: m.rss,
    heapUsed: m.heapUsed,
    heapTotal: m.heapTotal,
    external: m.external,
    arrayBuffers: m.arrayBuffers,
    heapLimit: getHeapStatistics().heap_size_limit
  };
}

Export these values as gauges in bytes at a modest sampling interval; memoryUsage can be expensive on large processes. Compare the time series to container memory usage and the configured limit. Container accounting can include file cache and other processes, so it is not interchangeable with RSS. On Linux with cgroup v2, memory.current and memory.events can provide additional evidence if the relevant cgroup files are accessible.

3. Read the shape of the growth

Production rule. A heap snapshot is useful for retained JavaScript objects, but it is not a complete account of container memory. Taking one can pause the process and require substantial additional memory. Use a disposable replica with sufficient headroom and protect snapshots as sensitive data.

4. Budget memory before configuring V8

Imagine a container with a 1024 MiB limit. A starting experiment might allocate 512 MiB to V8 old space, reserve 320 MiB for other heap spaces, native allocations, buffers and runtime overhead, and retain 192 MiB of headroom. These are illustrative budgets, not measured guarantees. The old-space flag is not a cap on the whole heap or process.

resources:
  requests:
    memory: "768Mi"
  limits:
    memory: "1Gi"
env:
  - name: NODE_OPTIONS
    value: "--max-old-space-size=512"

Requests influence scheduling; limits set an enforcement boundary. Measure peak usage with production-like traffic and adjust both based on evidence. Lowering old space too far can increase garbage collection and tail latency; raising it too far can crowd out native memory. Include rolling deployments in capacity calculations because old and new replicas may coexist.

5. Bound the workload, not merely the heap

Consider an endpoint that downloads and transforms files. Forty concurrent requests each buffering 12 MiB consume roughly 480 MiB before transformations, copies and overhead. Stream where possible, respect backpressure, cap input sizes and use a bounded concurrency limiter. Reject or defer work when the queue is full instead of accepting arbitrary amounts of memory-intensive work.

For Kafka consumers, bound concurrent processing and batch sizes, and monitor the downstream dependency that determines how quickly buffers can be released. For HTTP services, enforce request deadlines and ensure cancellation actually stops downstream work. Cache size limits should be expressed in a meaningful memory budget, not just a count of keys with wildly different value sizes.

6. Test the failure modes

Run a baseline with representative payloads, then ramp concurrency, introduce slow downstream responses and test maximum permitted request sizes. Include a sustained soak test to distinguish transient peaks from retained memory. Compare heap after collection, RSS, container memory, GC time, throughput, error rates and p99 latency. Verify recovery when the load falls. Run intentional OOM experiments only on isolated workloads.

Alert on sustained proximity to the container limit and on OOM termination events, not a single instantaneous heap percentage. Correlate restarts with deployment versions and workload changes. If a canary exceeds the memory or latency budget, roll back before the entire fleet repeats the experiment.

Takeaway. Treat memory as a capacity constraint across the runtime, container and workload. The goal is predictable behavior under pressure, not simply a larger number in a deployment manifest.

Official references

Related engineering notes