Skip to content

🚨 CRITICAL: Memory leak causes freeze after 20+ minutes (15GB RAM consumption) #21378

Open

Description

@wilhelmsson424-jpg

Claude Code CLI - Memory Leak Critical Bug Report

Date: 2026-01-28 04:45 UTC
Reporter: Rickard Wilhelmsson (wilhelmsson424@gmail.com)
Claude Code Version: Latest (2.1.21)
OS: Linux 6.6.87.2-microsoft-standard-WSL2 (WSL2)
RAM: 16GB total


🚨 CRITICAL: Claude process freezes after 20+ minutes, consuming 15GB RAM

Incident Summary

11th occurrence of Claude process completely freezing, requiring force kill (kill -9).

Symptom: Claude CLI becomes unresponsive, consuming 90%+ of system RAM, making entire system unusable.

Technical Details

Process Analysis (PID 718 - frozen instance):

VmSize:    89738368 kB (87.6 GB virtual memory)
VmRSS:     15024756 kB (14.7 GB resident memory)
Threads:   20
Open files: 371
Runtime:   40 minutes (frozen at 04:05-04:45)
CPU:       46.6% (stuck in processing loop)

Memory State at Freeze:

Total RAM:  15Gi
Used:       15Gi (100%)
Available:  46Mi (0.3%)
Swap:       2.8Gi used of 4.0Gi

Root Cause Analysis

Evidence from ~/.claude.json (project config):

{
  "numStartups": 303,
  "lastTotalCacheReadInputTokens": 9656824,  // 9.6 MILLION tokens
  "lastTotalCacheCreationInputTokens": 367980,
  "lastTotalInputTokens": 187950,
  "lastCost": 4.7301332
}

Findings:

  1. Unbounded cache growth:

    • Claude reads 9.6M tokens from conversation cache
    • ~35 MB raw text → 15GB in-memory after parsing/compilation
    • No garbage collection implemented
    • No cache size limits enforced
  2. Memory leak pattern:

    • Each session accumulates conversation history
    • After 303 startups, cache grows to critical size
    • Process never releases memory
    • Leads to swap thrashing → I/O bottleneck → freeze
  3. No recovery mechanism:

    • Once frozen, process cannot self-recover
    • Requires manual kill -9
    • Other Claude windows also affected (shared memory?)

Reproduction Steps

  1. Use Claude Code CLI extensively over weeks (300+ sessions)
  2. Work on complex tasks with long conversations
  3. Let conversation history accumulate (9M+ tokens cached)
  4. Start new session → Memory usage spikes to 15GB
  5. After 20-40 minutes → Complete freeze

Impact

User Impact:

  • Work interruption every ~30 minutes
  • Data loss if unsaved work in frozen window
  • System becomes unresponsive (swap thrashing)
  • Requires force kill, losing context

Frequency: 11 occurrences reported by user, likely more unreported

Attempted Workarounds

What DOESN'T work:

  • MCP server optimization (reduced startup from 28s to 6s, but freeze persists)
  • Direct SSH database access (bypassing MCP)
  • Reducing number of MCP servers

What DOES work (temporarily):

  • kill -9 (loses all context)
  • Manual cache cleanup (not user-friendly)

Proposed Fixes

Immediate (Hot-fix)

  1. Implement cache size limits:
const MAX_CACHE_TOKENS = 1_000_000; // 1M token limit
const MAX_HISTORY_LENGTH = 100; // Keep last 100 messages
  1. Add garbage collection:

    • Prune old conversation turns after threshold
    • Release memory for messages older than N hours
    • Implement LRU eviction for cached contexts
  2. Add memory monitoring:

    • Detect when process uses >8GB RAM
    • Warn user before freeze
    • Auto-cleanup if memory exceeds threshold

Long-term (Architecture)

  1. Streaming cache architecture:

    • Don't load entire conversation history into RAM
    • Stream from disk on-demand
    • Use memory-mapped files for large contexts
  2. Conversation chunking:

    • Split long conversations into chunks
    • Load only relevant chunks for current context
    • Implement smart context window management
  3. User-visible controls:

claude config set max-cache-size 1000000
claude cache clear
claude cache status

Diagnostic Data

System Info:

# Memory at freeze
$ free -h
               total        used        free      shared  buff/cache   available
Mem:            15Gi        15Gi        46Mi       2.0Mi        76Mi        46Mi
Swap:          4.0Gi       2.8Gi       1.2Gi

# Process state
$ ps aux | grep claude
rickard  718 46.6 94.5 91180160 15370036 pts/0 Rl+ 04:05 19:09 claude

# Cache stats from config
lastTotalCacheReadInputTokens: 9,656,824
lastTotalCacheCreationInputTokens: 367,980

MCP Servers Running (not the cause):

  • grokipedia (45MB RAM)
  • n8n-mcp (43MB RAM)
  • github (12MB RAM)
  • postgres (removed, was causing ECONNREFUSED but not freeze)

Total MCP overhead: ~100MB RAM (negligible)

Files for Investigation

Config:

  • ~/.claude.json (conversation cache metadata)
  • ~/.cache/claude-cli-nodejs/-home-rickard/ (cache files)

Logs:

  • ~/.cache/claude-cli-nodejs/-home-rickard/mcp-logs-*/

Example affected session:

  • Session ID: 7d66760d-6f8e-45eb-a0e1-bc99532b3576
  • Cost: $4.73
  • Cache read: 9.6M tokens

Workaround for Users (until fixed)

Emergency recovery:

# Find frozen Claude processes
ps aux | grep claude | grep -v grep

# Kill frozen process
kill -9 <pid>

# Clear cache manually (nuclear option)
rm -rf ~/.cache/claude-cli-nodejs/*/mcp-logs-*/*.jsonl

Prevention:

# Restart Claude daily to prevent cache buildup
# (Not ideal, loses context)

Request to Claude Team

Priority: CRITICAL (P0)

Ask:

  1. Implement hard limits on cache token count (1M tokens max)
  2. Add memory-aware garbage collection
  3. Provide user-facing cache management commands
  4. Document expected memory usage for long-running sessions

Contact:

Willing to provide:

  • Anonymized cache dumps
  • Memory profiling data
  • Beta testing of fixes

Generated: 2026-01-28 04:45 UTC
Status: Awaiting Claude Engineering review

Activity

  1. github-actions commented on Jan 28, 2026

    @github-actions

    Found 3 possible duplicate issues:

    1. [BUG] Session files grow unboundedly, causing OOM crash on startup ("Aborted (core dumped)") #20367
    2. [BUG] Unbounded session file growth from verbose command output causes 100% CPU + OOM crash on ANY session start #21179
    3. [BUG] Memory Leak from Unbounded Session File Growth #20200

    This issue will be automatically closed as a duplicate in 3 days.

    • If your issue is a duplicate, please close it and 👍 the existing issue instead
    • To prevent auto-closure, add a comment or 👎 this comment

    🤖 Generated with Claude Code

  2. wilhelmsson424-jpg commented on Jan 29, 2026

    @wilhelmsson424-jpg
    Author

    Additional Critical Data Point - OOM Kill at 15 Minutes Runtime

    Timestamp: 2026-01-29 07:20:47 (just occurred)

    OOM-killer log:

    Out of memory: Killed process 1024 (claude)
    - Total VM: 92711628kB (92.7 GB virtual)
    - anon-rss: 15668896kB (15.7 GB physical RAM)
    - Runtime: ~15 minutes
    - Cache tokens read: Unknown (process killed before monitoring started)
    

    Escalation:
    This is now the 12th confirmed OOM kill of Claude Code in production use. The memory leak is:

    • Faster: 15 minutes to OOM (vs previous 20-40 min)
    • Larger: 92GB virtual memory allocation
    • Blocking production work: Cannot complete multi-step tasks

    Business Impact:

    • Every Claude Code session lasting >15 min is at risk
    • No workaround exists (memory monitoring too slow)
    • Automated recovery scripts cannot prevent OOM-killer
    • Linux OOM-killer terminates process forcefully (no graceful shutdown)

    Request:
    Please prioritize this for next release. The issue makes Claude Code unusable for serious development work on Linux.

    Environment:

    • OS: WSL2 (Linux 6.6.87.2-microsoft-standard-WSL2)
    • Available RAM: 16GB
    • Claude version: Latest (Sonnet 4.5)
  3. wilhelmsson424-jpg commented on Jan 29, 2026

    @wilhelmsson424-jpg
    Author

    Update 2026-01-29 09:00 UTC: New Critical Bug - Agent Hang on Tool Confusion

    Summary

    Discovered a SECOND, SEPARATE bug that also causes memory leak + OOM-kill, distinct from the cache overflow issue.

    What Happened Today (Crash #13)

    Timeline:

    • 07:36:31 UTC: Agent a5ae718 started
    • 07:36:40 UTC: Agent attempted Skill("n8n-workflow-expert")
    • 07:36:41 UTC: System returned error: Unknown skill: n8n-workflow-expert
    • 07:36:41 UTC: Agent STOPPED RESPONDING (no further messages)
    • 07:36:46 Local: Memory leak began (613MB → 1097MB in 10 seconds)
    • 07:40:18 Local: RAM peaked at 15.1GB
    • 07:40:28 Local: System recovered (OOM-kill likely occurred)

    Total hang time: 4 minutes
    Memory leak rate: ~5GB/min (10x faster than cache leak)
    Evidence: Agent transcript agent-a5ae718.jsonl has only 7 lines, ending at the error with no recovery attempt

    Root Cause: Agent Error-Handling Failure

    1. Agent tried to use Skill("n8n-workflow-expert") (which doesn't exist)
    2. Received correct error: Unknown skill: n8n-workflow-expert
    3. Agent failed to handle the error:
      • No error response written
      • No recovery attempt
      • No fallback behavior
      • Complete hang
    4. Hung agent process continued running → memory leak → OOM-kill

    Note: n8n-workflow-expert exists as an agent (used with Task tool), not a skill (used with Skill tool). The agent confused the two tool types.

    Comparison: Two Separate Bugs

    Aspect Issue #21378 (Cache) Today's Bug (Agent Hang)
    Trigger Cache overflow (9.6M tokens) Wrong tool call (Skill vs Task)
    Symptom Gradual memory leak Instant hang → explosive leak
    Speed 1-2GB per 5 min 5GB per minute
    Recovery None (must restart) None (must restart)
    Bug Type Cache GC failure Agent error-handling failure

    Impact on Production Work

    • Frequency: Now experiencing crashes every 20-40 minutes (up from 40-60 min)
    • Blocking work: Cannot use agent system at all
    • Two attack vectors: Cache leak OR agent error = both → OOM-kill
    • User experience: 100% productivity loss during crashes

    Technical Details

    Agent transcript evidence:

    // Last message in agent-a5ae718.jsonl (line 7):
    {
      "type": "user",
      "message": {
        "content": [{
          "type": "tool_result",
          "content": "<tool_use_error>Unknown skill: n8n-workflow-expert</tool_use_error>",
          "is_error": true,
          "tool_use_id": "toolu_011eF5KXHAtb9S7qQm1NvsL3"
        }]
      },
      "timestamp": "2026-01-29T06:36:41.219Z"
    }
    // NO FURTHER MESSAGES - agent hung here

    Memory monitor log:

    07:36:36 - ✅ OK - RAM: 613MB
    07:36:46 - ✅ OK - RAM: 1097MB  (+484MB/10s)
    07:36:56 - ✅ OK - RAM: 2150MB  (+1053MB/10s)
    07:37:06 - ✅ OK - RAM: 3125MB  (+975MB/10s)
    07:37:36 - ⚠️  VARNING - RAM: 6156MB
    07:38:16 - 🚨 KRITISKT - RAM: 10041MB
    07:40:18 - 🚨 KRITISKT - RAM: 15042MB (peak before OOM)
    

    Recommended Fix (Claude Team)

    Immediate: Agent error-handling needs try/catch recovery:

    // Current (BROKEN):
    catch (error) {
      // No handling → agent hangs
    }
    
    // Fix:
    catch (error) {
      logger.error(`Tool error: ${error.message}`)
      await agent.sendMessage(`Error occurred: ${error.message}. Continuing without this tool.`)
      return fallbackBehavior()
    }

    Long-term protection:

    1. Agent timeout: Kill agent after 2 min no response
    2. Memory limit: Kill agent if >5GB RAM
    3. Force GC every 30 seconds
    4. Better error telemetry

    Workaround (User Side)

    Temporarily disabled agent system entirely to avoid both bugs:

    • No Task() calls
    • No Skill() calls
    • Direct tool usage only (Read, Edit, Bash)

    This is not sustainable for complex work but necessary until fix deployed.

    Request

    Please prioritize BOTH bugs:

    1. Original cache leak (🚨 CRITICAL: Memory leak causes freeze after 20+ minutes (15GB RAM consumption) #21378)
    2. NEW: Agent error-handling hang

    Both make Claude Code unusable for serious development on Linux. Combined, they cause crashes every 20-40 minutes.

    Full technical analysis available if needed.

  4. carpcarp commented on Jan 31, 2026

    @carpcarp

    I'm having the same issue except it rises about 5gb per 5 seconds and then crashes down to 7gb before climbing back to 20gb
    I'm happy to share nay logging if there's anything specific you'd like me to run. I tried filing a bug but the claude code freezes when running the report a bug command.
    Image

  5. cowwoc commented on Feb 3, 2026

    @cowwoc

    Here is a way to reproduce the crash immediately. Open claude code and paste the following:

    Use the Task tool to spawn a subagent with these exact parameters:

    • subagent_type: "general-purpose"
    • description: "test unknown skill"
    • prompt: "Call the Skill tool with skill='nonexistent-skill-xyz' and args='test'. Report any error you receive."

    Wait for the subagent result.

    Please update the title of this bug report to reflect the fact that a crash happens immediately, not after 20 minutes.

  6. michelesant82-beep commented on Feb 7, 2026

    @michelesant82-beep

    Additional data point: Windows native (WinGet) install - same memory leak pattern

    Environment:

    • OS: Windows 11 Pro (build 26200)
    • RAM: 32 GB
    • Claude Code: v2.1.34
    • Install method: WinGet (Anthropic.ClaudeCode) - native binary, no Node.js involved

    Observation:

    A session running for ~115 minutes accumulated 2.7 GB of resident memory before becoming completely unresponsive (frozen for 30+ minutes, no input accepted). No crash or OOM-kill occurred - the process stayed alive but non-functional.

    For comparison, a fresh session launched on the same machine uses ~690 MB, meaning the frozen session grew to ~4x its initial memory footprint.

    Process details (frozen session):

    PID=22432 | WS=2720.6 MB | Age=115 min | Threads=34 | CPU=2158s
    Binary: WinGet native package (not npm/node.js)
    

    Key difference from original report:

    • This is the native Windows binary (WinGet package), not the npm/Node.js version
    • No node.exe processes involved - the leak is in the native claude.exe binary itself
    • No WSL or Linux layer in the stack
    • Growth rate appears slower (~18 MB/min vs the 5 GB/min reported in the agent-hang variant), suggesting the gradual cache leak rather than the explosive agent-error leak

    Confirms: The memory leak is not Node.js-specific - it also affects the native Windows binary distributed via WinGet. This suggests the root cause is in shared application logic (conversation cache management), not in the Node.js runtime or Ink rendering layer.

  7. rafa-lopes-pt commented on Feb 15, 2026

    @rafa-lopes-pt

    UPDATE: RESOLVED
    Updating from Claude Code version 2.1.41 to 2.1.42 solved the memory leak problem. The issue no longer occurs with the latest version.


    System Details:

    • OS: Linux Mint 21.1 (Kernel 5.15.0-161-generic)
    • Architecture: x86_64
    • RAM: 16 GB
    • Claude Code Version: 2.1.41

    Issue:
    Experiencing severe memory leak in Claude Code that occurs even in brand new, empty project directories. Memory grows at approximately 50-60 MB/second during active conversation, leading to OOM kill within 5-15 minutes.

    Reproduction:

    1. Created fresh directory: mkdir ~/test-memory-leak && cd ~/test-memory-leak
    2. Started Claude Code: claude
    3. Had active conversation with tool calls (Read, Bash, WebFetch)
    4. Monitored with: watch -n 2 "ps aux | grep claude | grep -v grep"

    Observed Memory Growth:

    Time      VmRSS (RAM)    Growth
    00:05:33  5.67 GB        baseline
    00:05:35  5.77 GB        +100 MB/2s
    00:05:37  5.89 GB        +125 MB/2s
    00:05:39  5.99 GB        +100 MB/2s
    00:05:41  6.09 GB        +101 MB/2s
    

    Key Findings:

    • Heap allocation: 60.97 GB (VmData)
    • Baseline memory on startup: 1.36 GB
    • Project cache size: Only 71 KB (minimal - not the cause)
    • Leak rate: 50-60 MB/second consistently
    • Result: Process killed by OOM, swap exhausted (2GB/2GB)

    Critical Note:
    This is NOT a cache accumulation issue. The leak occurs in fresh projects with no accumulated cache, during runtime. The process heap grows unbounded during active conversation regardless of project history.

    Impact:
    Claude Code is currently unusable for any conversation lasting more than 5-10 minutes on a 16GB system. Multiple reproductions across different directories confirmed the same behavior.

  8. hirehamir commented on Aug 5, 2026

    @hirehamir

    Still-standing data point (Aug 04, 18:33 PDT): VS Code extension anthropic.claude-code 2.1.221 on Ubuntu 24.04 native (not WSL), 32 GB RAM + 24 GB swap.

    The extension's bundled binary (2.1.221) reached 11,867 MiB RSS and earlyoom killed it, plus 63 browser and 4 VS Code processes:

    Aug 04 18:33:39 earlyoom[1059]: mem avail: 801 of 32030 MiB ( 2.50%), swap free: 1775 of 24206 MiB ( 7.33%)
    Aug 04 18:33:39 earlyoom[1059]: sending SIGTERM to process 506018 uid 1000 "2.1.221": badness 1103, VmRSS 11867 MiB
    

    That session's transcript contains zero Grep tool calls and the process tree was ~3.5 h old, so this is consistent with a gradual heap leak as described in this issue.

  9. gboeer commented on Aug 19, 2026

    @gboeer

    I am using the vscode extension in a dev container and in my case the container crashes with an oom after only 2 minutes.
    If i deinstall the extension, the crash doesnt happen.

    This is the error message:
    "The window terminated unexpectedly (reason: 'oom', code: '-536870904')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions