Claude Code Memory Leak - Process Grows to 120+ GB RAM and Gets OOM Killed
Claude Code Memory Leak - Process Grows to 120+ GB RAM and Gets OOM Killed
Description
Claude Code has a severe memory leak that causes the process to grow to over 120GB of RAM before being killed by the Linux OOM killer. This happens consistently during extended coding sessions, approximately every 30-60 minutes of active use.
Environment
- Claude Code Version: 1.0.53
- OS: Ubuntu 24.04
- Kernel: Linux 6.14.11
- Total System RAM: 128GB
- Installation Method: Direct installation in home directory
Steps to Reproduce
- Start Claude Code in interactive mode
- Use it for an extended coding session (30-60 minutes)
- Perform typical operations: file reading, editing, searching, running bash commands
- Monitor memory usage with
ps aux | grep claude - Process will gradually consume all available RAM until OOM killed
Expected Behavior
Claude Code should maintain stable memory usage throughout the session, not exceeding a reasonable amount (e.g., 1-2GB for typical usage).
Actual Behavior
The claude process memory usage grows unbounded until it consumes all available system RAM (120+ GB) and triggers the OOM killer.
Evidence
OOM Kill Log Entries (from dmesg):
Killed process 1983785 (claude) total-vm:234427056kB, anon-rss:124857720kB, file-rss:0kB, shmem-rss:0kB, UID:XXXX pgtables:267248kB oom_score_adj:0
Killed process 1991601 (claude) total-vm:234453364kB, anon-rss:125118596kB, file-rss:596kB, shmem-rss:0kB, UID:XXXX pgtables:267880kB oom_score_adj:0
Killed process 1997049 (claude) total-vm:234463420kB, anon-rss:125275392kB, file-rss:5856kB, shmem-rss:0kB, UID:XXXX pgtables:269168kB oom_score_adj:0
Killed process 2001723 (claude) total-vm:234420884kB, anon-rss:119597028kB, file-rss:3748kB, shmem-rss:0kB, UID:XXXX pgtables:257104kB oom_score_adj:0
Killed process 2009167 (claude) total-vm:234464008kB, anon-rss:120216960kB, file-rss:372kB, shmem-rss:0kB, UID:XXXX pgtables:252260kB oom_score_adj:0
Key observations:
- total-vm consistently around 234GB (virtual memory)
- anon-rss (actual RAM used) between 119-125GB
- Multiple OOM kills in the same session indicate this is a recurring issue
- Memory consumption appears to be primarily anonymous pages (anon-rss), not file-backed
Impact
This memory leak makes Claude Code unusable for extended coding sessions as it:
- Causes system-wide memory exhaustion
- Triggers OOM killer which terminates other processes
- Loses session context when Claude is killed
- Requires frequent restarts, disrupting workflow
Additional Information
- The memory growth appears gradual over time, not sudden
- The issue persists across multiple sessions
- After OOM kill and restart, memory usage starts low (~400MB) and grows again
Potential Debugging Steps
To help diagnose this issue, the following information might be useful:
- Memory profiling of the claude process
- Heap snapshots at various points during execution
- Tracking of any unbounded data structures (conversation history, file caches, etc.)
Workaround
Currently, the only workaround is to periodically restart Claude Code before memory exhaustion occurs, which is highly disruptive to workflow.
---
Priority: High - This makes the tool unusable for its intended purpose of extended coding assistance
96 Comments
Found 3 possible duplicate issues:
If your issue is a duplicate, please close it and 👍 the existing issue instead.
🤖 Generated with Claude Code
does this was fixed? seems to be i had that too once, the IDE showed the notification e.g. out of memory.
I'm still having this issue regardless of where I run it. It's making CC hard to use, as it crashes machine after a while
I've been having this since I started using subagents (since version ~1.0.70).
Can't use more than 2 Claude Code instances because I ONLY have 32 GB of RAM.
me too..
I've solevd this by commiting to memory that CC should terminate any processes it's done using. I have stopped having issues.
thanks, bro. Can you explain more? Do you use CC hooks?
I am still seeing this on 1.0.98 where I've got 4 processes each taking about 2.5GB RAM
Environment
Issue Description
Claude Code process experiencing rapid memory growth leading to OOM kills. Monitoring shows memory jumps from stable baseline to crash threshold within minutes.
Memory Growth Pattern (from monitoring)
2025-10-11 18:46:48 PID:3174091 RSS:204MB VSZ:32120MB ← stable 2025-10-11 18:47:48 PID:3174091 RSS:1554MB VSZ:33467MB ← 7x jump in 60s 2025-10-11 18:48:48 PID:3174091 RSS:3967MB VSZ:35869MB ← nearly doubled 2025-10-11 18:49:48 PID:3174091 RSS:4301MB VSZ:36201MB ← crash threshold [Process killed by OOM]
Historical OOM Kills
10+ kills over 2 days (Oct 3-5):
Sample kern.log Entry
2025-10-05T14:12:52 kernel: Out of memory: Killed process 1418229 (claude) total-vm:36857676kB, anon-rss:4102880kB, file-rss:3048kB, shmem-rss:0kB, UID:1001 pgtables:119712kB oom_score_adj:0
Impact
System unusable for extended Claude Code sessions. Process requires restart every 30-60 minutes to prevent OOM.
Monitoring Setup
Created automated monitoring script logging memory every 60s to track growth patterns.
I got a record 34 GB yesterday on my Mac M1 Max 32 GB!
<img width="478" height="118" alt="Image" src="https://github.com/user-attachments/assets/b1e674ab-7b6b-4acc-b0e1-e55181f65f3f" />
97gb here :)
<img width="824" height="62" alt="Image" src="https://github.com/user-attachments/assets/86c64c8c-14e5-4172-bf48-6a2f7b30bb56" />
on
v2.0.27Yesterday my claude instance got up to 107GB after a few hours of very intensive work and took down my whole machine.
Consistently getting 130GB+
and sometimes VS Code just crashes UI
!Image
Only 2 VS Code windows are running simultaneously...
UPD. I think it was audio and ntfy hooks (asked CC to optimize them and remove ntfy)
<img width="1070" height="40" alt="Image" src="https://github.com/user-attachments/assets/0bd4228d-0b9c-42b6-a315-3d39eafdbb8c" />
Related?
My CC shows that on every startup right away
This issue has been inactive for 30 days. If the issue is still occurring, please comment to let us know. Otherwise, this issue will be automatically closed in 30 days for housekeeping purposes.
up
Here because i've seen it 128GB RAM and recently started getting "Your system has run out of application memory" -- it's claude code. 120GB+ !!
On Mac it spins up dozens and dozens of
claudeinstances each with ~250mb memory usage. I'm using the VS Code extension, and it seems to partially help to close tabs and re-open them, but only partially. It's really really annoying and leads to the system eventually filling swap to the point it's unusable and I have to reboot.This is killing my machine also with over 100 gb of memory being used by zombie processes. I agree it makes it usable....
up
please fix <3
Can't tell if it's CC or WSL in my case
happens to me via powershell but not on wsl
This just started to hit me yesterday and today (7-Jan 26 and 8-Jan 26). Currently one command (with sub-agents) has 5 processes with 48GB, 40GB, 40GB, 31GB and 10GB used on by 64GB Mac. Using iTerm2, if it matters.
For me, the problem emerges when I'm using agents. I have a command that starts an agent a number of times and claude ram usage goes from ~500MB to 25GB. The memory explosion happens during a random turn, i.e. the same agent runs for five times, no problem, then it blows the memory on 6th and claude code prints out
Aborted()then it gets into a hung state. Sometimes it happens only at the second, third run of the same agent. You get the idea. This is claude code running under a docker container, backed by WSL2 on Windows 10 professional.If I run the command that is run by the agent (the one that is run repeatedly by the original, root command) manually, then I have no problems. So this is what's failing:
Command X -> [Agent -> Command Y] (1..* times)and this is what's working without any problems :
Human user -> Command Y (1..* times)Similar here, just on a quite simple session in Debian 12
2026-01-15T10:15:29.621397+01:00 d22-bak kernel: [ 4274.306390] oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=unattended-upgrades.service,mems_allowed=0,global_oom,task_memcg=/user.slice/user-1000.slice/session-1.scope,task=claude,pid=6910,uid=0
2026-01-15T10:15:29.621398+01:00 d22-bak kernel: [ 4274.307076] Out of memory: Killed process 6910 (claude) total-vm:60651380kB, anon-rss:31224120kB, file-rss:2432kB, shmem-rss:0kB, UID:0 pgtables:71052kB oom_score_adj:0
2026-01-15T10:15:31.225465+01:00 d22-bak kernel: [ 4276.586764] oom_reaper: reaped process 6910 (claude), now anon-rss:0kB, file-rss:232kB, shmem-rss:0kB
In my case, the memory issue (on the latest occasion) was caused by Claude Code attempting to read block device files directly (/dev/sda5, /dev/sdb5 - 1.8TB partitions) using the Read tool, instead of using appropriate commands like lsblk or lvs.
Environment:
What happened:
The process attempted to read 1.8TB block devices as regular files, causing:
[ERROR] Error: ENOMEM: not enough memory, read '/dev/sda5'
[ERROR] Error: ENOMEM: not enough memory, read '/dev/sdb5'
Process state:
Workaround applied:
Added deny rules to /.claude/settings.local.json to prevent Read tool from accessing block devices:
Suggestion:
The Read tool should validate that file paths don't point to block devices before attempting to read them, or at least fail gracefully instead of trying to allocate terabytes of memory.
Wow. Why would Claude Code go up the file system beyond the current directory at all to begin with?
My lucky day today...
Similar issue but different root cause - GC Infinite Loop Freeze:
Environment:
What happened:
After executing an I/O intensive command (rsync), the Claude Code process entered an infinite Garbage Collection loop and became completely
unresponsive. The rsync command completed successfully, but the process never returned to a responsive state.
Process state:
Root cause analysis:
The issue appears to be a Garbage Collector implementation bug where:
This is NOT I/O blocking (state D) and NOT a memory leak - it's a GC infinite loop that freezes the session completely.
Workaround:
Only option is to kill the process: kill <pid> and restart session. No way to recover the frozen session.
Suggestion:
The Garbage Collector should have timeout mechanisms or better handling of large object collection to prevent infinite loops that freeze the entire session.
No. 71G is VIRT and it's relatively useless to diagnose problems. On Linux you look at RSS and its modern alternatives such as RSan and the memory use reported by cgroups (e.g. through systemd-cgtop)
Same issue here, ram just grows.
This has been such an annoying issue. Even closed Claude Code sessions remain idle in the background, taking up memory and slowing things to a crawl over time 😕
In case anyone finds it helpful, this is the current patch I'm using! With 3 tiers depending on how much you want to automate it:
Simplest, straightforward:
ps aux | awk '($11 ~ /\/claude$/ || $11 == "claude") {print $2}' | while read pid; do [[ $(ps -p "$pid" -o stat= 2>/dev/null) != *"+"* ]] && echo "$pid"; done | xargs -r kill 2>/dev/nullps aux | awk '($11 ~ /\/claude$/ || $11 == "claude") {print $2}' | xargs kill 2>/dev/nullAlternatively a script with various features you can call from the command line or Apple Shortcuts (kill only idle processes, kill all, list all processes, kill all except current session you're running script from, etc.): https://github.com/yulonglin/dotfiles/blob/main/custom_bins/clear-claude-code
And lastly if you want to clear idle Claude Code sessions in the background periodically (macOS or Linux): https://github.com/yulonglin/dotfiles/blob/main/scripts/cleanup/setup_claude_cleanup.sh
Problem for me, is even if I kill them. When I bring them back via --resume, CPU goes pinned 100% again. So it kinda kills the whole session long term.
Really annoying when you're working on important things and need to keep a high mem/high cpu session alive to finish the work.
_Known Causes of Memory Leaks in 2.1.x
Persistent Conversation History: The application accumulates conversation data in ~/.claude/projects/ without a cleanup mechanism, causing it to load massive files into memory on startup or resume._
Cleaning this folder helped solve it for me.
You might want to create new Claude Code sessions as opposed to just relying on compacting. For example, you could ask Claude to summarise or write down in some docs what was done this session, and start afresh another session. Afaik fresh Claude Code sessions shouldn't be affected by
~/.claude/projects, as it's just disk spacethis was not compacting related, I had done a full reboot, start a fresh session and then still direct memory bloat. After deleting a large portion of these files, which had grown to over 8GB, the problem was solved.
Confirming exploding ram usage in Linux Ubuntu x64 KVM. Completely Unusable. Acquired via VSCode extension. Rolled back to 2.1.20 and works correctly. At least until 2.1.25 did not work at all presenting leak issue
+1 having the same issue
macOS as well
The leak happens randomly. I think it is related to it reading large config files. I asked Claude to read a large file and it started to leak.
When it's leaky due to changed configs,
claude installleaks too<img width="746" height="784" alt="Image" src="https://github.com/user-attachments/assets/70613cf2-3588-4de4-b413-3a3047857b0f" />
The programs written by Claude are running in the terminal, but it forgot to close them. It is also possible that the timeout settings were set too long, preventing them from being closed in a timely manner.
I've already restarted my MacBook three or four times today because the memory usage exceeded 120GB.
Yeah, this is still an issue in version 2.1.34. Nothing like getting OOM with 128GB of RAM and a 128GB swap file, which I turned on just to try to catch this and give me time to kill it.
I use ulimit and docker ram limit (which works though a different kernel facility of control groups). You can use a method specific to your OS. 4GB ought to be enough for everyone.
Yes but this folder is much less than 128GB when the leak starts. And it contains the knowledge Claude accumulated over time so starting from scratch is a bad option although it's better than nothing.
Seems still to be an issue. I am on Windows and opening the Ubuntu terminal via WSL, and I can see VmmemWSL jumps to 100% and gets killed.
In my case, claude was keeping the output of a large build script in ram. By asking it to run the build script in the background and periodically check on it, the log is saved to disk, and claude no longer crashes
@TheNewJavaman How large was the log? I doubt any of the reporters have logs worth dozens of GBs of the leak. The memory efficiency of log storage may be abysmal. In that case, it would be a clear performance bug.
Crazy how it just leaks when you leave it open for a long time. I had one process get to 13GB. The team should really look into this.
Claude Code installer crashes with OOM on systems with <4GB RAM
Environment
curl -fsSL https://claude.ai/install.sh | bashIssue
Installation fails with process killed at line 142 of install script:
Root Cause
The
claudebinary attempts to allocate excessive memory during installation:The installer tries to allocate ~88GB virtual memory and ~3.6GB RAM, exceeding available system resources.
Expected Behavior
Installation should complete on systems with 4GB RAM without requiring swap space or excessive memory allocation.
The logs can be several GB, and in this scenario, Claude had to run the build script several times. Should I open a new issue?
@nponeccop
I don't work for Antropic I was just wondering. This bug says "has repro" so they are working on it and your bug may or may not be a duplicate. It's safer to leave it here until they resolve this issue
There is no Assignee on this isssue, and Anthropic has not commented on it, so we cannot assume anyone is "working on it".
It may even be that this issue will soon get closed with "60 days of inactivity" https://github.com/anthropics/claude-code/issues/16497.
My turn to report this issue:
I have 96 GB of ram -- and this was mallocing 135 GB (and had 80 resident). Quite nuts.
I've just had a long chat with Claude Opus 4.6 about this (Web, because my Claude Code environment is currently inoperable). Most of my Claude use is via Code, so if this isn't fixed soon (rather than just via a "sticky plaster" like more RAM or "give it swap") then it's no longer worth paying for, presumably time to try Codex... Claude(Web)'s Summary...
Claude Code v2.1.39 — OOM Kill on Launch in Memory-Constrained Linux VM
Summary
Claude Code v2.1.39 is killed by the Linux OOM killer within approximately 90 seconds of launch, before any user input is processed. The process allocates ~70GB of virtual memory and consumes ~3.6GB of physical RSS during what appears to be initialisation/indexing, exhausting all available RAM in a 4GB VM with no swap.
This is consistent with the memory regression introduced around v2.1.8 and reported across multiple issues, but notably this environment previously ran Claude Code without issue for months on the same 4GB/2-CPU allocation. The regression appeared with recent version updates.
Environment
| Component | Detail |
|-----------|--------|
| Claude Code version | 2.1.39 |
| Host OS | macOS (Apple Silicon M2 Pro Mac mini, 32GB RAM) |
| Virtualisation | Lima using Apple's Virtualization.framework (
vz) || Guest OS | Ubuntu 22.04 Server (arm64/aarch64) |
| Kernel | 5.15.0-170-generic #180-Ubuntu |
| VM CPUs | 2 |
| VM RAM | 4 GiB |
| Swap | None (Lima default — no swap configured) |
| Model configured |
opusplan(ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-4-6) || Default permission mode |
plan|| MCP Servers | GitHub (multiple instances, read-only PAT) |
Reproduction
limactl shell claudecd /Users/Quintinwillison/code/QuintinWillison/plan-viewer/claudeKilledand drops back to the bash prompt.No user input is required — the kill happens during or immediately after initialisation. The
plan-viewerrepository is a small project; this is not a large monorepo.100% reproducible. Two consecutive OOM kills were captured in a single session.
OOM Kill Evidence
Kill #1 — 14:57:40 UTC
Kill #2 — 15:00:20 UTC (second launch attempt)
System Memory State at Kill
From the kernel's
Mem-Infodump at the time of the second kill:The process table at kill time shows
claudeas overwhelmingly the largest consumer:929,656 pages × 4KB = ~3.55 GB RSS — the claude process alone consumed approximately 89% of total physical RAM.
Key Observations
total-vmis consistently ~73.9 GB across both OOM events, suggesting a deterministic allocation pattern rather than a random leak.plan-viewer) is a small codebase, not a monorepo with hundreds of thousands of files.Configuration Files
Lima VM Definition (
lima.yaml)Claude Code Settings (
settings.json)Impact
Claude Code is completely unusable in this environment without workarounds (increasing VM RAM, adding swap, or pinning to an older version). For users running Claude Code in memory-constrained Linux VMs — which is a reasonable deployment given Claude Code's own documentation suggesting modest resource needs — this is a blocker.
And then, like magic, Claude Code upgraded itself to version
2.1.41and the issue has disappeared. What on earth is going on over there? This feels less like "bleeding edge" and more like "chaos" to me. Or was it a server-side issue causing client-side OOMs?Like magic indeed. I've got five sessions running, and things are holding rock steady. I looked through the release notes and didn't see anything that addressed this directly. I guess Claude doesn't like commenting on Claude issues.
Nor closing them if they're resolved. 😬 This repo is up to 5K now. Amazingly my high CPU loop (idle after typing
/) is also gone, so I guess that update had some major improvements.I too am having this issue, it seems to only be background tasks that are causing it.
Detailed analysis from aarch64 Linux (Hetzner VPS)
Environment: Claude Code v2.1.42, Node.js v22.19.0, aarch64 (ARM64), Ubuntu 24.04, 32 GB RAM
Symptom: Single Claude Code session reached 29.9 GB RSS in ~18 minutes of active use (multi-step coding task with MCP tool calls). Killed by systemd tmux cgroup scope (
tmux-spawn-*.scope). Hit twice on the same box — first at 16 GB, then after upgrade to 32 GB.Key findings from
/proc/<pid>/smaps_rollupand/proc/<pid>/status:| Metric | Value |
|--------|-------|
| VmPeak | 129.2 GB |
| VmRSS at kill | 29.9 GB |
| Anonymous (heap+buffers) | ~21 GB outside V8 |
| V8 pointer cage | 54 GB rw-p mapping (mostly 0 KB RSS) |
|
--max-old-space-size| 8192 (baked into SEA binary) || Processes in cgroup | 13 (identical to idle session) |
Root cause analysis:
--max-old-space-size=8192only caps V8 old generation heap, not total process RSS. Memory allocated via Node.js Buffers, ArrayBuffers, native C++ addons, libuv, and stream pipelines is unbounded.--max-old-space-sizenot being properly respected (related to V8's memory cage behavior on ARM64).What works as mitigation:
systemd cgroup
MemoryMaxis the only reliable hard cap. Example for tmux scopes:Or for existing sessions:
This forces the OOM killer to target the Claude process before it takes down the entire box. V8's GC _should_ respond to memory pressure signals from cgroup, but the non-V8 allocations won't.
Bottom line:
--max-old-space-sizeis necessary but insufficient. Claude Code needs either (a) a built-in cgroup/ulimit wrapper, or (b) explicit tracking and limits on non-V8-heap allocations (Buffers, streams, native addons).macOS M2 Pro (32GB) — 13 concurrent sessions, v2.1.44, stable under memory compressor
Adding a data point from a heavy concurrent-session macOS setup that's currently stable, with findings that may help others — particularly the correct environment variable for the current Bun/JSC build.
Environment
Per-session RSS (all 13 sessions)
Swap used: only 233 MB of 1 GB total. Memory pressure: green.
macOS memory compressor achieves a 2.4x compression ratio (storing ~6.3 GB of logical data in 2.6 GB of physical compressor pages). Cumulative swap activity: 2.3M swapouts / 1.4M swapins over 21h — steady but not pathological.
Key finding:
BUN_JSC_forceRAMSizeis the correct env var, notNODE_OPTIONSCurrent Claude Code (v2.1.44) ships as a compiled Bun binary using JavaScriptCore (JSC), not V8. I confirmed this via binary inspection — the compiled binary contains
BUN_JSC_env var parsing code,--smolflag strings, and Bun FFI signatures.The
NODE_OPTIONS="--max-old-space-size=8192"workaround that's been widely suggested in this thread and others has no effect on the Bun build. The JSC equivalent is:This constrains JSC's perception of available RAM, causing garbage collection to run more aggressively before memory grows to dangerous levels. Without it, JSC on a 32GB machine won't meaningfully GC until ~25.6 GB — by which point you're deep into swap or OOM territory.
The value should be tuned based on your RAM and concurrent session count. On a 32GB machine running up to 5 sessions, 16 GB is a reasonable setting — JSC triggers hard GC at ~12.8 GB per process, well before the 34 GB+ runaway leaks reported in this thread. Lower values (e.g., 8 GB) trigger GC earlier but add more CPU overhead during normal operation.
What helped stabilise our setup
/exitbefore closing terminals to avoid orphaned processes (#17391). Ctrl+C leaves subagent processes runningBUN_JSC_forceRAMSizeset as aboveWhy macOS reports may be rarer
macOS users are likely more resilient to this leak because the memory compressor provides ~2.4x headroom that Linux doesn't have. On our 32GB M2 Pro, 13 sessions averaging ~450 MB each = ~5.9 GB RSS, which the compressor handles without meaningful swap pressure. Linux users on equivalent RAM hit OOM much sooner with no transparent compression layer. This may explain the Linux-heavy distribution of reports in this thread.
SSD wear note
For anyone concerned about swap impact on Apple Silicon SSDs: our 1TB NVMe shows 269 TB lifetime writes at 11% wear (SMART data). Apple's SSDs are rated for 600+ TBW. The swap churn from multiple Claude sessions is measurable but not alarming for SSD endurance, even with daily heavy use.
Follow-up: Correction and better workarounds
After further testing, I need to correct part of my earlier comment.
BUN_JSC_forceRAMSize: honest reassessment
I ran controlled stress tests allocating JS strings (which model the actual Claude Code leak pattern — conversation context and tool output retention):
RSS was identical in both cases. The env var did not reduce actual memory consumption. This is because large JS strings in Bun/JSC are backed by native memory (mimalloc), not the JSC garbage-collected heap. Since Claude Code's memory growth comes primarily from retained strings (conversation context, subprocess output, tool results),
BUN_JSC_forceRAMSizelikely has limited practical effect on this specific leak.The 80% GC threshold is real (verified in WebKit source:
criticalGCMemoryThreshold = 0.80), but it only governs JSC heap objects, not native string backing stores.I'm leaving the original comment for context, but don't expect
BUN_JSC_forceRAMSizeto solve the memory leak. It may provide marginal benefit for JSC-managed objects but won't address the primary leak vector.Better workarounds (verified in v2.1.44 binary)
I found these in the Claude Code source (confirmed via binary inspection):
1.
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE— probably the most effectiveThis triggers context compaction at 50% of the context window instead of the default ~83.5%. Since the documented root cause of gradual memory growth is conversation context accumulation (one user in #18011 reported a 35 MB session file with 1,467 JSONL entries before crash), compacting earlier directly reduces the retained object graph. Verified in binary source — the function reads
process.env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE, parses it as a percentage, and adjusts the compaction threshold.2. Session restarts between major tasks
The only guaranteed fix. The leak is cumulative — each subprocess call, tool result, and context compaction cycle adds retained data that GC cannot reclaim. Restarting resets everything.
3. Active session management
Kill idle sessions. Each idle session still runs MCP polling and background operations that accumulate memory. On my setup, reducing from 13 to 5 sessions drops total RSS from ~5.9 GB to ~2.3 GB.
Note for npm/Node.js users
My earlier comments focused on the native Bun binary. If you installed Claude Code via npm and see V8 stack traces in your crashes,
BUN_JSC_forceRAMSizedoes nothing for you. UseNODE_OPTIONS="--max-old-space-size=8192"instead, which is the V8 equivalent. TheCLAUDE_AUTOCOMPACT_PCT_OVERRIDEworkaround works for both installation methods.Correction to my previous correction: Do NOT lower autocompact threshold
Retracting the
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50recommendation from my previous comment. In practice, lowering the compaction threshold significantly degrades session quality — Claude loses conversation context earlier, which impacts its ability to track complex multi-step tasks, remember prior decisions, and maintain coherence across long sessions.The default ~83.5% threshold exists for good reason. Compacting earlier trades memory for intelligence, which is the wrong tradeoff for most users.
What actually works (honest assessment)
After testing multiple approaches, the verified mitigations for this leak are all operational, not configuration-based:
/exitbefore closing terminals — Ctrl+C leaves orphaned subagent processes that balloon to 34 GB+ (#17391).What doesn't work
BUN_JSC_forceRAMSize— GC hint only, no effect on RSS in stress tests (see my previous correction)CLAUDE_AUTOCOMPACT_PCT_OVERRIDE— reduces memory but destroys session qualityNODE_OPTIONS— irrelevant on the native Bun binaryThe real fix
This needs to be addressed architecturally by Anthropic. The core issue — unbounded retention of subprocess stdout/stderr and conversation context in native memory — has no user-side workaround that doesn't sacrifice functionality. The data in this thread (61+ reports across every platform) makes the case clearly.
What users can contribute: per-session RSS data, reproduction cases, and version-specific regression/improvement reports help narrow the scope. The v2.1.41/42 improvements reported by several commenters suggest progress is being made, even if undocumented.
For what it's worth, a big contributor to the RAM growth is bloated session JSONL files — sessions with recursive grep outputs, progress tick duplication, and large tool outputs can easily hit hundreds of MB. I've been running cozempic as a guard daemon that continuously prunes session bloat, which keeps file sizes manageable and noticeably reduces the memory pressure. Not a fix for the underlying leak, but it helps keep sessions from becoming the trigger.
If you're looking for an automated workaround while waiting for an official fix, I open-sourced a three-layer cleanup solution:
claude-ram(check RAM breakdown) andclaude-cleanup(manual kill)Repo: https://github.com/theQuert/claude-code-cleanup
One-command install:
./install.shIn practice, I found 21 orphan processes (subagents + MCP servers + claude-mem workers) consuming ~4 GB that were cleaned up instantly. The daemon runs via
brew servicesso it auto-starts on boot.This issue has been a major pain point for me too. On macOS, after a day of Claude Code sessions I regularly see 7+ GB eaten by orphaned subagents and MCP servers (PPID=1, no controlling TTY).
I built cc-reaper to deal with this systematically:
awk '$7 == "??"'to target only true orphans without a TTY)claude-ram— quick RAM breakdown by category (CLI sessions / subagents / MCP servers)claude-cleanup— manual kill for immediate reliefTypical orphan breakdown I've measured:
| Process | RAM each |
|---------|----------|
|
claude --output-format stream-json(subagent) | 180–300 MB || MCP servers (supabase, context7, etc.) | 40–110 MB |
|
chroma-mcp --client-type persistent| ~350 MB ||
worker-service.cjs --daemon| ~100 MB |One-line install:
Not a root cause fix, but it keeps things manageable until process lifecycle is handled properly upstream. Hope this helps anyone else drowning in orphaned processes.
@theQuert I wonder if you can use PGID to reliably track the children
getting this
<img width="382" height="47" alt="Image" src="https://github.com/user-attachments/assets/e7321cfa-3f19-4c93-9569-0f847acc9296" />
and then this
<img width="927" height="61" alt="Image" src="https://github.com/user-attachments/assets/ab731616-26e4-4c9a-bd1b-de6eac2b80f8" />
@nponeccop Great suggestion! I investigated PGID behavior on a live system and confirmed that Claude Code sessions are indeed process group leaders (PGID = session PID), and all spawned MCP servers, subagents, and their children inherit this PGID.
This means a single
kill -- -$PGIDreliably cleans up everything — including third-party MCP servers that pattern matching might miss.I've implemented PGID-based cleanup as the primary detection method across all three layers in v0.4.0:
claude-cleanup: Finds orphaned process groups where the PGID leader has PPID=1, kills entire groups at oncePattern-based detection is kept as a fallback for edge cases where processes escape their group via
setsid().Verified on macOS with multiple concurrent sessions — each session's children (MCP servers, subagents, npm exec processes) all share the parent's PGID consistently.
@cesarvarela If you're looking for an automated solution, cc-reaper can handle this — it's a three-layer cleanup tool specifically for orphaned Claude Code processes:
It sets up a Stop hook (auto-cleanup on session end), a background daemon (catches crashes), and shell commands like
claude-cleanup(instant kill) andclaude-ram(RAM usage breakdown). Uses PGID-based process group detection so it catches all children reliably.This is awesome! Thank you.
I have the same issue but I am on Windows 11
Same here. I ran Opus on the /heapdump got the below results. Since the project isn't opensource can't validate any of this. Hopefully it helps out.
same here, 2 minutes and it grew to 7 gigs of ram usage
@rublev Glad it helps! Let me know if you run into any edge cases.
@EduardoGNQ cc-reaper currently targets macOS (uses
launchd,ps -eo pgid, etc.), but the core detection logic (PGID-based group cleanup + pattern fallback) should be portable. If there's interest in Windows/WSL support, PRs or even just "here's what breaks on my setup" reports are very welcome — tracking this as a potential expansion: https://github.com/theQuert/cc-reaper/issues@saif97 This heapdump analysis is incredibly valuable — the 7,073 × 256KB ArrayBuffer retention pattern and the closure-captured
Responseobjects pinpoint the upstream root cause much more precisely than anything I've seen in this thread. This kind of data makes a strong case for Anthropic to fix the streaming consumption path.From the cc-reaper side, this actually validates why process-level cleanup matters as a stopgap: if each session leaks at ~42 GB/hr, killing idle/orphaned sessions early is the only user-side lever that actually reclaims memory. cc-reaper's
claude-guardfunction (auto-reaper for idle sessions) + the stop hook + proc-janitor daemon together address exactly this — preventing leaked sessions from accumulating to the point where the system becomes unusable.If you'd like to contribute your heapdump methodology or findings to the repo (even as a docs reference), that would be a great addition for users trying to understand why their RAM is disappearing.
@WERDXZ 7 GB in 2 minutes is brutal. If you're on macOS,
cc-reapercan at least keep things from spiraling — the background daemon scans every 30s and kills orphaned process groups automatically:After install, run
claude-ramto see your current breakdown by category (sessions / subagents / MCP servers / orphans).---
For anyone following this thread: cc-reaper is actively maintained and we welcome contributions — whether it's new platform support, better detection heuristics, or upstream analysis like @saif97's heapdump work. Repo: https://github.com/theQuert/cc-reaper
Unfortunately I'm on linux... @theQuert I'll be trying to debug this if I have time
@WERDXZ PGID works on Linux as well. But on Linux there are cgroups and there are a few advices (e.g. https://github.com/anthropics/claude-code/issues/4953#issuecomment-4049174081 ) on how both limit the memory usage and kill it with all children
for macOS users hitting this - the heap command is useful for tracking what's actually growing:
heap <PID> > /tmp/heap1.txt
wait 10-15 minutes
heap <PID> > /tmp/heap2.txt
diff by type+size to find what's accumulating
we run multiple Claude Code agents in parallel via launchd (4 scheduled workflows, each spawning a claude process) and ran into similar growth patterns. Instruments is too expensive for high-allocation processes - heap snapshots with a time gap between them show you exactly which object types are accumulating without the overhead.
for the OOM kill specifically, on Linux cgroups are the right containment. on macOS we ended up just monitoring with a background daemon that checks RSS every 30s and kills orphaned process groups when they cross a threshold
we run 4 parallel Claude agents via launchd on macOS. the scheduling setup: https://github.com/m13v/social-autoposter/tree/main/launchd - each plist triggers a shell script that spawns a claude process with --max-turns. the multi-agent orchestration: https://github.com/m13v/tmux-background-agents
Pretty incredible that this bug has been there for over 6 months without being fixed. Team? You there?
By the way the tag
platform:linuxis totally inaccurate. I'm on macOS and have this bug as well.@m13v Great heap profiling tip! Running 4 parallel Claude agents via launchd is exactly the scenario where orphan processes pile up fast. cc-reaper has a
claude-guardfunction designed for this — it monitors all sessions' RSS in real-time and auto-kills any that exceed a configurable threshold (default 4GB) using PGID group kills, so all child processes (subagents, MCP servers) get cleaned up together. Since you're already using launchd for scheduling, the proc-janitor daemon layer should fit right into your workflow.@josefguenther Agree this has been painful for way too long, and you're right — it's definitely not Linux-only. While waiting for an official fix, cc-reaper provides automated defense on macOS with three layers: a stop hook (cleans up when sessions end), a background daemon (scans every 30s for orphan processes), and
claude-guard(auto-reaper that kills bloated sessions exceeding an RSS threshold). One-line install, pure shell — no extra runtime needed.@WERDXZ For Linux, the core shell functions in cc-reaper (
claude-cleanup,claude-guard,claude-ram) work cross-platform since they rely on standardpsand PGID-based kills. The macOS-specific part is the launchd daemon layer — a Linux systemd unit would be a straightforward addition. If you're interested, feel free to open an issue at https://github.com/theQuert/cc-reaper and we can work on systemd integration together.A session cleanup hook can help prevent memory accumulation:
A
Notificationhook can also clean up on session start:These hooks won't fix the core memory leak (which is in the Claude Code process itself), but they can:
/compactor restart before OOM kills the processThe 120+ GB RAM usage comes from Claude Code parsing massive JSONL session files. Sessions accumulate progress ticks, file-history snapshots, duplicate system-reminders, and base64 image blocks that balloon file size.
Cozempic v1.4.1 keeps session files lean with a guard daemon that auto-prunes via 17 strategies. The
image-stripstrategy alone removes old base64 screenshots (keeps last 20%).progress-collapseeliminates thousands of progress tick messages.compact-summary-collapseremoves everything before the last compaction boundary (85-95% savings).pip install cozempic && cozempic initThe guard auto-starts on every session via the SessionStart hook — just install and forget. Would be curious if anyone here sees memory usage drop after running it on their bloated sessions.
High virtual memory ~~usage~~ size happens even on a fresh installation, it's enough to start
claudeand let it wait.In the past (https://github.com/anthropics/claude-code/issues/12987#issuecomment-3969148746) also high resident memory was used by a fresh claude instance, so the above hypothesis
The 120+ GB RAM usage comes from Claude Code parsing massive JSONL session filesis not covering all cases.The screenshot below is from Almalinux 9 virtual machine and
2.1.118 (Claude Code)with a fresh installation of claude, and without any model work done, onlyclaudestarted in a terminal, without claude/login.<img width="1047" height="258" alt="Image" src="https://github.com/user-attachments/assets/489a91da-ff2c-48fe-ac0d-61772f5f8a9d" />
Cross-reference: filed #60534 with the same symptom on v2.1.143 on WSL2 (Ubuntu 24.04). RSS grew from ~900 MB to 12.6 GB in ~12 minutes of normal interactive use; exiting and restarting fully releases the memory. Also seen:
claude updateitself consumed 14.8 GB before being killed and left a 0-byteversions/2.1.144. Adding here for visibility — same root cause likely.Same issue here
@marcindulak VIRT is not "virtual memory usage". High VIRT in
topon a 64-bit system is high address space reservation and it's not a sign of any memory problem, so this report is invalid.OK, updated my comment from "virtual memory usage" to "virtual memory size", and added a mention of resident memory too. My point was that since the high (resident) memory size was high even during the fresh claude installation, 3rd party tools that remove local claude session files are not covering all cases, and there is still something unusual about claude's high memory usage. By a fresh installation I mean installing claude with
curl -fsSL https://claude.ai/install.sh | bashon a new virtual machine, no claude login yet, and it's notclaude update, there is nothing under~/.claude.I should had posted instead this image https://github.com/anthropics/claude-code/issues/12987#issuecomment-3969148746 that includes high resident memory during a fresh claude installation, but that was the situation in February 2026 for me. This high memory usage during claude installation still continues today (with
2.1.159 (Claude Code)), I believe partly randomly, only sometimes the virtual machine freezes during the claude installation. It's not even clear the problem is resident memory, but maybe a network or disk usage caused by the claude installation.<img width="1178" height="294" alt="Image" src="https://github.com/user-attachments/assets/65137f1b-703d-449e-aa38-273cc02df560" />
Correction to my previous comment: The crash log I shared was AI-generated and contained an incorrect timeline. The actual situation is much worse than "8 hours idle":
Real Timeline (from kernel journal)
Claude Code crashes within minutes of launch, not after hours of idle time. On June 9 alone, it was OOM-killed 8 times in one afternoon:
And again on June 10 at 12:38.
Systemd scope confirms rapid death
The process runs for only ~5 minutes before consuming 14.5 GB and getting killed. This is not an idle-time leak — it is a rapid memory explosion during normal use.
Every kill shows the same pattern
total-vm: ~70 GB (virtual address space)anon-rss: 276 kB to 47 kB (almost no physical anonymous memory)unevictable shmem: 12-14 GB (unreclaimable shared memory)The unevictable shmem mechanism I described in my previous comment still applies — the correction is about when it happens: minutes after launch, not hours of idle.
Another data point: v2.1.173, Linux native binary, long agent sessions reach 31–33 GB RSS
Environment
claude --resume, with heavy tool output (data-analysis workloads producing large stdout)Observation
During long sessions the
claudeprocess RSS grows monotonically to 31–33 GB and never shrinks. Growth correlates with accumulated conversation history — especially large tool outputs — being kept in the heap for the lifetime of the session. There is no built-in cap, andNODE_OPTIONSheap flags have no effect (presumably because it's a Bun-compiled native binary, not stock Node).Workarounds we've landed (in case they help others)
claudein a systemd scope so a runaway session pressures/kills only itself instead of OOMing the box:``
bash
`claude() {
systemd-run --user --scope -q \
-p MemoryHigh=16G -p MemoryMax=24G \
"$(command -v claude)" "$@"
}
MemoryHighapplies reclaim pressure;MemoryMaxhard-kills. Since--resume` restores the session (session id survives), a hard kill is recoverable./proc, sums RSS of claude-named processes only (excluding work subprocesses), and past a threshold (we use 8 GB) does a clean stop + relaunch with--resume. This keeps long-lived agent runs bounded indefinitely.Ask: a configurable memory ceiling, plus paging/compacting older conversation history (especially large tool results) out of the resident heap, would address the root cause.
--resumealready proves session state can live on disk.Hitting this on the Linux CLI too — adding hard kernel-level evidence, since most reports
here describe the symptom but not the proof.
Kernel OOM log (the smoking gun):
kernel: claude invoked oom-killer ... constraint=CONSTRAINT_NONE ... global_oom
Out of memory: Killed process <pid> (2.1.178) total-vm:19128004kB,
anon-rss:16990848kB ... # ~16.2 GB resident, anonymous
So this is an off-heap / native RSS leak killed by the kernel — not a V8 heap-limit
crash. (Same off-heap mechanism as #67433.)
The key data point: process RSS is fully decoupled from session size.
gap. So this is not "big session -> big RAM"; it's unbounded native growth.
claudeprocesses on the same host sit at ~0.9 GB RSS, roughly constantacross very different session sizes. The crashed one was the lone outlier.
commhad been renamed to a version-like string (2.1.178), notclaude— worth noting for process-monitoring: filtering oncomm == "claude"missesthe ballooned process. Match by UID or open-fd instead.
Trigger: the OOM landed on the turn right after ingesting an ~86 KB image — clearly the
spike that tipped an already-bloated process, not the cause. Strain was visible beforehand
(tool ops running 10-100x slower for minutes = memory pressure).
Containment != fix: on a no-swap host this is an instant kill with no graceful
degradation. Adding swap + a per-cgroup
MemoryMaxcontains it (degrades / self-OOMs onesession instead of freezing the host), but the underlying native growth in long-lived
sessions is unaddressed and recurs regardless of host config.
I haven't seen the leak lately - many sessions survive a weekend while inactive.
Adding a datapoint with kernel-level evidence (macOS jetsam report).
Environment: Claude Code 2.1.201 (native/bun build), macOS 26.2, Apple Silicon, 24GB RAM. Large Nx/TypeScript monorepo (~6GB working tree). Six concurrent CC sessions in terminal tabs, each running for several hours with subagent fan-out and occasional long build/typecheck Bash tasks.
Outcome: kernel JetsamEvent followed by two WindowServer userspace watchdog timeouts → GUI crash / forced logout. All six sessions lost.
Jetsam snapshot (top residents at time of event):
~86GB RSS across the six main CC processes alone on a 24GB machine; the compressor was holding ~145GB of uncompressed anonymous pages with ~150MB free when jetsam fired.
rpages≈lifetimeMaxon every bun process — they grew monotonically and never released.Notes that may help triage:
Happy to pull specific fields out of the JetsamEvent
.ipsor run a heapdump on a fresh session if that's useful.