Prevent Claude Code Cost Explosion

Claude Code can burn through your entire quota in minutes when it gets stuck in a loop. This page shows the real problem and the hooks that prevent it.

The Problem: Runaway Loops

Real Incident: 80% quota consumed in minutes

GitHub Issue #38335 (80+ reactions): Users reported their Max plan session limits exhausting abnormally fast — sometimes 80% consumed within minutes of starting a session.

Real Incident: Usage explosion

GitHub Issue #37917: Extreme token consumption where a simple task consumed the entire session budget.

Common causes:

Solution 1: Tool Call Rate Limiter

The tool-call-rate-limiter hook blocks tool calls when the frequency exceeds a threshold (default: 30 calls per 60 seconds).

#!/bin/bash
# tool-call-rate-limiter.sh — PreToolUse hook
RATE_FILE="${HOME}/.claude/rate-limiter.log"
MAX_CALLS="${CC_RATE_LIMIT_MAX:-30}"
WINDOW="${CC_RATE_LIMIT_WINDOW:-60}"

mkdir -p "$(dirname "$RATE_FILE")"
NOW=$(date +%s)
CUTOFF=$((NOW - WINDOW))

echo "$NOW" >> "$RATE_FILE"
RECENT=$(awk -v cutoff="$CUTOFF" '$1 >= cutoff' "$RATE_FILE" | wc -l)

awk -v cutoff="$CUTOFF" '$1 >= cutoff' "$RATE_FILE" > "${RATE_FILE}.tmp"
mv "${RATE_FILE}.tmp" "$RATE_FILE"

if [ "$RECENT" -gt "$MAX_CALLS" ]; then
    echo "BLOCKED: $RECENT calls in ${WINDOW}s (max: $MAX_CALLS)" >&2
    exit 2
fi
exit 0

Solution 2: Consecutive Error Breaker

The consecutive-error-breaker hook warns after N consecutive non-zero exit codes (default: 5), detecting stuck retry loops.

#!/bin/bash
# consecutive-error-breaker.sh — PostToolUse hook
EXIT_CODE=$(echo "$(cat)" | jq -r '.tool_result.exit_code // "0"')
STATE_FILE="/tmp/cc-error-streak"
MAX="${CC_ERROR_STREAK_MAX:-5}"

if [ "$EXIT_CODE" = "0" ]; then
    echo "0" > "$STATE_FILE"; exit 0
fi

CURRENT=$(cat "$STATE_FILE" 2>/dev/null || echo "0")
echo $((CURRENT + 1)) > "$STATE_FILE"

if [ $((CURRENT + 1)) -ge "$MAX" ]; then
    echo "⚠ $((CURRENT + 1)) consecutive errors. Try a different approach." >&2
fi
exit 0

Solution 3: Daily Usage Tracker

The daily-usage-tracker hook records every tool call and warns at milestones (100/250/500/1000 calls per day).

Install All Three

One command installs 655 example hooks including all cost protection hooks:

npx cc-safe-setup --install-example tool-call-rate-limiter

npx cc-safe-setup --install-example consecutive-error-breaker

npx cc-safe-setup --install-example daily-usage-tracker

Or install everything: npx cc-safe-setup --shield

Related Hooks

Related Pages

Learn more: Production Guide · All Tools