All Articles Claude Code

Cost Management for Claude Code in CI/CD

So you've decided to integrate Claude Code into your GitHub Actions workflows. Smart move—automated code generation, testing, and documentation can save hours of manual work.

So you’ve decided to integrate Claude Code into your GitHub Actions workflows. Smart move—automated code generation, testing, and documentation can save hours of manual work. But here’s the question that keeps engineering managers awake at night: How much is this actually going to cost?

The truth is, running Claude in CI/CD can get expensive fast if you’re not intentional about it. A single large codebase scan, a poorly optimized prompt, or a runaway workflow that triggers on every commit can rack up hundreds of dollars in token costs in minutes. But here’s the good news: with the right strategies, you can slash your API costs by 80% while actually improving your workflow efficiency.

In this article, we’re going to walk through exactly how Claude Code pricing works, show you concrete ways to calculate costs for your specific use cases, and give you battle-tested techniques to optimize token consumption without sacrificing quality. Whether you’re running linters, generating documentation, or performing code reviews in CI/CD, these strategies will help you stay within budget while getting maximum value from Claude’s intelligence.

Understanding Claude Code Pricing Fundamentals

Before we optimize, you need to understand how you’re being charged. Claude uses a token-based pricing model, which means every interaction costs money—input tokens for what you send, output tokens for what Claude generates. Token costs vary dramatically based on which model you use and how many tokens your request requires.

Token Cost Breakdown

Here’s the current pricing structure across Claude’s model lineup (as of March 2026):

Claude Haiku 4.5 (fastest, cheapest):

  • Input: $1 per million tokens
  • Output: $5 per million tokens

Claude Sonnet 4.5 (balanced):

  • Input: $3 per million tokens
  • Output: $15 per million tokens

Claude Opus 4.5 (most capable, most expensive):

  • Input: $5 per million tokens
  • Output: $25 per million tokens

Most teams use Sonnet for CI/CD work—it offers the best balance between intelligence and cost. Haiku works great for simple tasks like linting or basic refactoring, while Opus is overkill for automation (save it for interactive work where you need maximum reasoning capability).

Model choice matters: Using Opus instead of Sonnet for a simple lint check costs 1.67x more with no corresponding quality improvement. At scale, this inefficiency multiplies.

What Counts as a Token?

One token is roughly 4 characters of text. So a 100-character variable name is about 25 tokens. Your entire Git diff? Easily 10,000+ tokens. Your project’s README? 500 tokens. This is why context management becomes critical in CI—every file you include in your prompt burns tokens.

Token estimation: A typical PR diff of 400 lines of code = 2,000-4,000 tokens depending on code density and language. If your entire project is 100 files averaging 500 lines each, that’s 50,000 lines = 200,000+ tokens. Sending all of that to Claude would cost $0.60+ per request.

Hidden Costs: The Extended Context Premium

Here’s a gotcha that trips up most teams: if your prompt exceeds 200,000 tokens, Claude charges a higher rate for input tokens. Sonnet’s rates jump to $6 input / $22.50 output per million tokens in the extended context window. This is why you can’t just dump your entire monorepo into Claude and expect reasonable costs.

Real-world scenario: A team sends a 250,000-token codebase (1.25x the threshold). They pay extended pricing on 50,000 tokens = +$0.15 extra per run. On 20 runs, that’s $3 wasted. Scale to 50 teams and it’s $150 per day.

Prompt Caching (Your Secret Weapon)

This is where the real savings come from. Claude offers prompt caching—you write context once, Claude caches it, and subsequent requests reuse that context at 90% savings.

Here’s how it works:

  • Write a cache: 1.25x the base input price (for 5-minute cache) or 2.0x (for 1-hour cache)
  • Read from cache: 0.1x the base input price

Concrete example: Say you run 10 code reviews in a single CI/CD job, all against the same style guide (3,000 tokens).

Without caching:

  • 10 reviews × 3,000 tokens × $3/million = $0.09

With caching:

  • Initial write: 3,000 tokens × $3 × 2.0 = $0.018
  • 9 reads: 3,000 × 9 × $3 × 0.1 = $0.081
  • Total: $0.099 (slightly higher on this small scale)

But if you run 100 reviews? Caching saves you $0.81. At scale, caching is a game-changer. For a team running 50 code reviews daily across multiple repositories, caching the same standards documents saves thousands per month.

When caching pays off: Any static context that appears in 5+ requests per day should be cached. Style guides, testing frameworks, API documentation, architectural principles—all candidates.

Calculating Real-World Costs for Your Workflows

Theory is nice, but what do actual workflows cost? Let’s build a cost calculator based on real scenarios.

Scenario 1: Single Code Review in CI

You want Claude to review each PR automatically.

What you’re sending Claude:

  • PR diff: ~4,000 tokens (average medium PR)
  • Your code style guide: ~2,000 tokens
  • Security checklist: ~1,000 tokens
  • System prompt: ~500 tokens
  • Total input: ~7,500 tokens

What Claude generates:

  • Detailed review with suggestions: ~2,000 tokens

Cost calculation (using Sonnet):

  • Input: 7,500 × $3 / 1,000,000 = $0.0225
  • Output: 2,000 × $15 / 1,000,000 = $0.03
  • Total per review: $0.0525

If you merge 10 PRs per day across your team:

  • Daily cost: $0.525
  • Monthly (22 working days): ~$11.55
  • Annually: ~$138.60

That sounds cheap until you realize you have 15 repositories and 50 engineers. Suddenly it’s $10,000+ per year per small company. Now multiply by inefficient prompt design (full codebase context instead of just diffs), and you’re at $20,000+.

Scenario 2: Automated Test Generation

You want Claude to generate test cases for new code.

Inputs:

  • New function code: ~500 tokens
  • Existing test examples: ~3,000 tokens
  • Testing framework guide: ~1,500 tokens
  • Total: ~5,000 tokens

Output:

  • Generated tests: ~4,000 tokens

Cost per run (Sonnet):

  • Input: 5,000 × $3 / 1M = $0.015
  • Output: 4,000 × $15 / 1M = $0.06
  • Per run: $0.075

Running this on every commit across 5 repositories:

  • 50 commits/day average
  • Cost: 50 × $0.075 = $3.75/day or $82.50/month

This is actually reasonable, but here’s the catch: if you include the full testing framework documentation (10,000 tokens instead of 1,500), it becomes $0.18 per run = $7.50/day = $165/month. Double the cost for the same output quality.

Scenario 3: Documentation Generation at Scale

Generate API docs from code every time you deploy:

Inputs:

  • Full API codebase: ~20,000 tokens (this is where costs explode)
  • Documentation template: ~2,000 tokens
  • Total: ~22,000 tokens

Output:

  • Complete API documentation: ~8,000 tokens

Cost per generation (Sonnet):

  • Input: 22,000 × $3 / 1M = $0.066
  • Output: 8,000 × $15 / 1M = $0.12
  • Per run: $0.186

If you generate docs 5 times weekly:

  • Cost: 5 × $0.186 = $0.93/week or ~$48/month

But if you include unnecessary files (node_modules code samples, generated types, etc.), you could easily inflate this to 40,000 tokens and triple the cost to ~$0.50 per run = $129/month.

Lesson: Context bloat is expensive.

Quick Cost Reference Table

Task Input Tokens Output Tokens Cost/Run Cost/Month (10x/day)
PR Review 7,500 2,000 $0.053 ~$11.66
Test Generation 5,000 4,000 $0.075 ~$16.50
Lint Check 3,000 500 $0.0105 ~$2.31
Doc Generation 22,000 8,000 $0.186 ~$41
Security Scan 15,000 3,000 $0.090 ~$19.80

Note: Costs shown using Sonnet 4.5; multiply by roughly 10x for Opus, divide by 3x for Haiku.

Why this matters: These are baseline costs. Real-world costs depend heavily on how you structure your prompts and how much context you include.

Strategy 1: Optimize Your Prompts

The fastest way to reduce costs is to stop sending unnecessary tokens to Claude. Every character counts.

Include Only Relevant Context

Most teams make this mistake: they send Claude their entire codebase as context.

Bad approach:

# Sends entire repo structure + all files
- name: Review PR
  run: |
    find . -type f -name "*.js" -o -name "*.json" | \
    xargs cat | \
    claude-code review --context=all

You’re paying for tokens that Claude won’t even use. Instead:

Good approach:

# Send only the changed files
- name: Review PR
  run: |
    git diff HEAD~1 HEAD | \
    claude-code review --diff-only

This reduces input tokens from ~50,000 to ~5,000. Same quality review, 90% cheaper.

Real impact: On a team doing 20 code reviews per day, using --diff-only vs. full context saves ~$9/day = ~$200/month. That’s $2,400 per year per team.

Use Targeted System Prompts

Instead of a 2,000-token system prompt that covers everything, build task-specific prompts.

Expensive (2,000 tokens):

You are an expert code reviewer. Check for:

- Security issues
- Performance problems
- Code style violations
- Test coverage gaps
- Documentation issues
- Design patterns
- Accessibility concerns
  ...and 20 more things

Efficient (400 tokens):

You are a security code reviewer.
Check for: SQL injection, XSS, authentication,
authorization, crypto errors, sensitive data leaks.
Return only findings with risk level and fix.

Running a security scan? Use the security prompt. Checking style? Use the style prompt. You’ll save tokens and get better results (Claude isn’t context-switching between conflicting goals). A focused prompt also produces more focused output—fewer tangents, clearer recommendations.

Token savings: 2,000 vs. 400 = 1,600 tokens per request. 20 requests/day = 32,000 tokens saved = $0.10/day = $2.20/month. Scales to $110/year.

Truncate Large Outputs

Claude outputs are expensive. If you request detailed explanations but only need summaries, you’re wasting output tokens.

Expensive request:

Please analyze this function and provide:

1. Full explanation of what it does
2. Potential issues and why
3. Suggested improvements with examples
4. Performance analysis
5. Security considerations

This generates 3,000+ tokens of output.

Efficient request:

Analyze this function. Return only: issues (max 3,
prioritized by risk), fixes (1-line each). No explanations.

This generates 500-800 tokens of output.

Adding output constraints cuts Claude’s response size by 70%. Token savings: huge. You still get actionable feedback—you don’t need Claude to explain why an issue is bad, just what needs fixing.

Concrete savings: 3,000 output tokens (Sonnet @ $15/M) = $0.045 per run. 30 runs/day = $1.35/day = $29.70/month = $356/year.

Use Structured Output (JSON Mode)

Force Claude to return structured data instead of prose. It’s cheaper because Claude uses fewer tokens for “here’s the JSON” than for paragraph explanations.

- name: Generate Issues
  run: |
    claude-code analyze --format=json \
      --output-schema='{"issues": [{"line": int, "type": string, "fix": string}]}'

You get parseable output and save tokens. Win-win. Structured output also makes downstream processing easier—you can programmatically extract specific data without parsing prose.

Why it matters: Code that parses JSON is more reliable than code that parses prose. No ambiguity about where the findings start or end.

Strategy 2: Implement Caching Strategically

Prompt caching is your leverage point for cost reduction at scale. The trick is knowing what to cache.

Cache Static Context

Any context that doesn’t change between runs is a caching candidate.

Example: Style guides

# First run (writes cache)
- name: Review PR
  env:
    CACHE_KEY: style-guide-v2
  run: |
    STYLE_GUIDE=$(cat ./standards/style-guide.md)
    claude-code review \
      --cache-key="$CACHE_KEY" \
      --context="$STYLE_GUIDE" \
      --file="${{ github.event.pull_request.head.sha }}"

The first PR in the day: 2.0x cost on the style guide tokens.

All subsequent PRs: 0.1x cost on the style guide tokens.

Cache hit rate in typical CI: ~70-80% (multiple PRs, builds, reviews daily).

Real savings:

  • Style guide: 2,000 tokens
  • Initial write: 2,000 × $3 × 2.0 / 1M = $0.012
  • 9 cache hits: 2,000 × 9 × $3 × 0.1 / 1M = $0.054
  • Without caching (10 runs): $0.06. With caching: $0.066. Cost neutral at small scale.

But on 100 runs per month? Caching saves $0.45.

Across 50 teams? That’s $22.50/month saved on one guide. Multiply by 10 guides = $225/month = $2,700/year.

Cache Frequently-Reused Models and Examples

Testing frameworks, API documentation, design patterns—anything you reference repeatedly is a caching candidate.

# In your workflow, at the start of each job
- name: Cache Test Examples
  run: |
    TEST_FRAMEWORK=$(cat ./docs/jest-examples.md ./docs/mocha-patterns.md)
    echo "TEST_FRAMEWORK_CACHED=true" >> $GITHUB_ENV

Then in subsequent steps, reference the cached context instead of re-sending.

Caching strategy: Identify your top 5 most-referenced documents. Cache all of them. This single change often cuts token usage by 30-40% for large workflows.

Set Appropriate Cache TTLs

Claude offers two cache durations:

  • 5-minute cache (1.25x write cost): Good for workflows that run repeatedly in rapid succession
  • 1-hour cache (2.0x write cost): Good for daily/weekly static contexts

When to use 5-minute:

  • Multi-step linting jobs that run tests, then security scans, then documentation
  • Parallel workflows that might access the same style guide
  • Rapid iteration during development

When to use 1-hour:

  • Style guides, framework documentation
  • Shared team standards
  • Security checklists
  • Company-wide best practices

The 1-hour cache costs more to write (2.0x vs. 1.25x) but amortizes better across the day. If you’re generating docs 50 times per day, the 1-hour cache’s higher write cost is quickly offset by cache hits.

Math: 1-hour cache on 3,000-token guide: write cost = $0.018, hit cost = $0.0009/hit. 50 hits = $0.0009 × 50 = $0.045. Total = $0.063. No-cache cost = 50 × $0.009 = $0.45. Savings = $0.39. That’s 6x better.

Strategy 3: Control Workflow Triggers and Concurrency

The biggest cost killers in CI aren’t poor prompts—they’re workflows that run too often or in parallel.

Trigger Selectively

Most teams set Claude workflows to run on every commit. That’s not necessary.

Current (expensive):

on:
  push:
    branches: [main, develop] # Runs on every push
  pull_request: # Runs on every PR

Optimized:

on:
  pull_request:
    paths:
      - "src/**" # Only if source code changed
      - ".github/**" # Only if workflows changed
    branches: [main]
  schedule:
    - cron: "0 1 * * *" # Daily at 1am for comprehensive scans

This reduces runs by 70% without losing coverage.

Concretely: Instead of running on every push to every branch (100+ runs/day), trigger only on PRs to main (10-20 runs/day). Add a nightly schedule for comprehensive analysis. You catch issues without paying for noise.

Add Concurrency Limits

Running 20 code reviews in parallel? That’s 20x the tokens at once, potentially hitting rate limits.

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

This ensures only one workflow runs per branch. Plus, if you push a new commit before the previous review finishes, the old one cancels, saving tokens.

Smart concurrency: If you push 5 commits in rapid succession, the old runs cancel. Instead of 5 review runs = $0.26, you get 1 run = $0.05. Savings = $0.21 per iteration.

Stagger API-Heavy Tasks

Don’t run documentation generation, testing, and linting all in parallel. Stagger them:

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - run: claude-code lint

  test-gen:
    runs-on: ubuntu-latest
    needs: lint
    steps:
      - run: claude-code generate-tests

  docs:
    runs-on: ubuntu-latest
    needs: test-gen
    steps:
      - run: claude-code generate-docs

Sequential execution means cache hits are higher (same static context reused across jobs), and you avoid rate limit issues. You’re paying for better resource utilization.

Rate limit protection: Most CI/CD providers have rate limits (e.g., 100 parallel requests). Running tasks sequentially keeps you under limits and prevents expensive retry loops.

Strategy 4: Choose the Right Model for the Task

Using Opus for style checking is like hiring a Michelin-star chef to make toast. Haiku can handle 80% of CI tasks.

Haiku for Simple Tasks

Good Haiku tasks (costs ~1/3 of Sonnet):

  • Linting and formatting checks
  • Style guide validation
  • Simple refactoring suggestions
  • Comment generation
  • Basic test generation
  • Changelog writing
  • Finding imports and exports
  • Counting lines of code

Example workflow:

- name: Style Check
  run: claude-code lint --model=haiku-4.5

- name: Generate Tests
  run: claude-code test-gen --model=haiku-4.5

Cost difference: $0.05 for Sonnet becomes $0.015 for Haiku. Save $0.035 per run × 20 runs/day = $0.70/day = $15.40/month.

When Haiku struggles: Complex security analysis, architectural decisions, refactoring legacy code. For these, Haiku produces surface-level suggestions. Sonnet digs deeper.

Sonnet for Medium Complexity

Sonnet tasks:

  • Code reviews with security considerations
  • Complex refactoring suggestions
  • Architecture recommendations
  • Performance optimization
  • Comprehensive documentation
  • Understanding unfamiliar codebases

Sonnet is intelligent enough for 90% of real-world work without the Opus overhead.

Opus Only When Necessary

Opus is overkill for CI. It’s better for:

  • Interactive debugging sessions
  • Complex architectural decisions
  • Novel problem-solving
  • Learning new frameworks

You shouldn’t be running Opus in CI at all. Save it for your interactive work where you can leverage its reasoning power.

Dynamic Model Selection

Based on task complexity, switch models:

- name: Analyze Complexity
  id: analysis
  run: |
    COMPLEXITY=$(git diff HEAD~1 HEAD | wc -l)
    if (( COMPLEXITY < 100 )); then
      echo "MODEL=haiku-4.5" >> $GITHUB_OUTPUT
    elif (( COMPLEXITY < 500 )); then
      echo "MODEL=sonnet-4.5" >> $GITHUB_OUTPUT
    else
      echo "MODEL=opus-4.5" >> $GITHUB_OUTPUT
    fi

- name: Review Code
  run: claude-code review --model=${{ steps.analysis.outputs.MODEL }}

Smaller diffs use cheaper models. Bigger, complex changes get Sonnet’s intelligence. You automatically optimize cost-per-task.

Real-world impact: 70% of PRs are small (< 100 lines), so they use Haiku. 20% use Sonnet. 10% get Opus if genuinely complex. Average cost drops from Sonnet-everywhere to ~$0.04 per review.

Strategy 5: Implement Budget Alerts and Rate Limiting

You can’t optimize what you don’t measure.

Set Up API Usage Monitoring

Most teams rely on their Anthropic bill to know they’re overspending. By then it’s too late.

Instead, track token usage in real-time:

- name: Log Token Usage
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: |
    USAGE=$(claude-code usage --format=json)
    echo "Input tokens: $(echo $USAGE | jq '.input_tokens')"
    echo "Output tokens: $(echo $USAGE | jq '.output_tokens')"
    echo "Estimated cost: $(echo $USAGE | jq '.estimated_cost')"

Write this to a file, commit it to a metrics/ branch, and review weekly. You’ll spot trends before they become problems.

Set Per-Workflow Budgets

GitHub Actions has no native token budget enforcement, but you can build one:

#!/bin/bash
# budget-check.sh

ESTIMATED_COST=$(claude-code estimate-cost --workflow=$1)
BUDGET=$2

if (( $(echo "$ESTIMATED_COST > $BUDGET" | bc -l) )); then
  echo "❌ Estimated cost ($ESTIMATED_COST) exceeds budget ($BUDGET)"
  exit 1
else
  echo "✅ Cost ($ESTIMATED_COST) within budget ($BUDGET)"
fi

Then in your workflow:

- name: Check Budget
  run: bash .github/scripts/budget-check.sh "code-review" "0.50"

If estimated cost exceeds $0.50, the workflow fails. No surprise bills.

Enforcement value: A failed budget check forces you to optimize before deploying. You catch inefficiencies before they compound.

Use GitHub Secrets to Limit API Keys

Create separate Anthropic API keys with different rate limits. Assign them to different workflows:

  • CODE_REVIEW_API_KEY: 100k tokens/day (for PR reviews)
  • DOCS_API_KEY: 50k tokens/day (for doc generation)
  • LINTING_API_KEY: 30k tokens/day (for linting)

If a workflow goes rogue and burns through its limit, only that workflow is affected. You lose one feature, not everything.

Safety benefit: Rate limiting creates blast radius containment. A bug in one workflow can’t drain your entire budget.

Strategy 6: Implement Caching Beyond Prompts

Most teams think “caching” means prompt caching. But there’s a bigger opportunity: caching outputs.

Cache Generated Code

If Claude generates the same boilerplate repeatedly, cache the output instead of regenerating it.

- name: Generate Boilerplate
  id: boilerplate
  run: |
    # Check if we've generated this before
    CACHE_FILE=".github/cache/boilerplate-${BOILERPLATE_TYPE}.json"
    if [ -f "$CACHE_FILE" ]; then
      cat "$CACHE_FILE"
    else
      # Generate new and cache
      RESULT=$(claude-code generate-boilerplate --type=$BOILERPLATE_TYPE)
      mkdir -p .github/cache
      echo "$RESULT" > "$CACHE_FILE"
      echo "$RESULT"
    fi

For repeated scaffolding tasks (new API endpoints, database migrations, form components), caching outputs saves 100% on token costs. You pay once, reuse infinitely.

Concrete case: A team generates 20 new endpoints per sprint, each using the same boilerplate. Generate once ($0.10 in tokens), cache it (free), use it 19 times (free). Cost = $0.10 instead of $2.00.

Cache Analysis Results

Code quality metrics, security scan results—if they haven’t changed, reuse them.

- name: Security Scan (with Cache)
  run: |
    CACHE_KEY="security-$(git rev-parse HEAD)"
    CACHE_FILE=".github/cache/security-${CACHE_KEY}.json"

    if [ -f "$CACHE_FILE" ]; then
      echo "Using cached results"
      cat "$CACHE_FILE"
    else
      RESULT=$(claude-code security-scan ...)
      mkdir -p .github/cache
      echo "$RESULT" > "$CACHE_FILE"
    fi

Only re-run when source code changes. Zero token cost for no-change builds.

Impact on CI: On a team with multiple CI jobs, this cuts token usage by 30-50% because many builds don’t actually change code (rebases, dependency updates, branch protections, etc.).

Putting It All Together: A Complete Optimized Workflow

Let’s build a real workflow that incorporates all these strategies.

name: Code Quality with Cost Management

on:
  pull_request:
    paths:
      - "src/**"
      - ".github/**"
  schedule:
    - cron: "0 1 * * *"

concurrency:
  group: code-quality-${{ github.ref }}
  cancel-in-progress: true

jobs:
  style-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Check Budget
        run: |
          BUDGET=0.20
          ESTIMATED=0.05  # Haiku is cheap
          if (( $(echo "$ESTIMATED > $BUDGET" | bc -l) )); then
            exit 1
          fi

      - name: Style Check with Haiku
        env:
          ANTHROPIC_API_KEY: ${{ secrets.LINTING_API_KEY }}
        run: |
          git diff HEAD~1 HEAD > /tmp/diff.txt
          claude-code lint \
            --model=haiku-4.5 \
            --diff-only \
            --cache-key="style-guide-v2" \
            --output=json \
            /tmp/diff.txt

  code-review:
    runs-on: ubuntu-latest
    needs: style-check
    steps:
      - uses: actions/checkout@v4

      - name: Review with Sonnet
        env:
          ANTHROPIC_API_KEY: ${{ secrets.CODE_REVIEW_API_KEY }}
        run: |
          git diff origin/main HEAD > /tmp/pr.diff

          # Cache the style guide (1-hour TTL)
          STYLE_GUIDE=$(cat ./standards/style-guide.md)

          claude-code review \
            --model=sonnet-4.5 \
            --cache-key="style-guide-v2" \
            --cache-ttl=3600 \
            --context="$STYLE_GUIDE" \
            --output=json \
            /tmp/pr.diff > /tmp/review.json

      - name: Comment Review on PR
        uses: actions/github-script@v7
        with:
          script: |
            const review = require('./tmp/review.json');
            github.rest.pulls.createReview({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number,
              body: review.summary,
              comments: review.comments
            });

  test-generation:
    runs-on: ubuntu-latest
    needs: style-check
    steps:
      - uses: actions/checkout@v4

      - name: Generate Tests
        env:
          ANTHROPIC_API_KEY: ${{ secrets.CODE_GEN_API_KEY }}
        run: |
          # Only if tests are missing
          CHANGED_FILES=$(git diff HEAD~1 HEAD --name-only | grep src/)

          for FILE in $CHANGED_FILES; do
            TEST_FILE="${FILE%.js}.test.js"
            if [ ! -f "$TEST_FILE" ]; then
              claude-code generate-tests \
                --model=haiku-4.5 \
                --cache-key="jest-examples-v1" \
                --output="$TEST_FILE" \
                "$FILE"
            fi
          done

Cost breakdown for this workflow per PR:

  • Style check (Haiku): $0.015
  • Code review (Sonnet, cached guide): $0.035
  • Test generation (Haiku, if needed): $0.045
  • Total: ~$0.095 per PR

With 10 PRs/day: $0.95/day or $20.90/month for comprehensive CI/CD automation.

Compare to an unoptimized workflow:

  • Style check (Sonnet, full context): $0.08
  • Code review (Opus, no caching, full context): $0.30
  • Test generation (Sonnet): $0.15
  • Total: ~$0.53 per PR = $5.30/day = $116/month

Your optimization saves $95/month for the same work. That’s $1,140/year.

Common Pitfalls and How to Avoid Them

Pitfall 1: Sending Too Much Context

The biggest mistake teams make: “Give Claude everything, let it figure it out.”

What happens: Your 100-file codebase becomes 200,000+ tokens. $0.60+ per run. 50 runs = $30 down the drain.

Fix: Send only changed files. Use git diff not git diff HEAD~100. Be surgical. A PR should never include the entire codebase.

Pitfall 2: Forgetting to Implement Caching

Teams set up prompt caching, run a few workflows, then turn it off because it “seems slow.”

What happens: The first request takes 2-3 seconds (cache write), but subsequent ones are instant (cache read). Teams see the slow first request and revert, losing 90% savings.

Fix: Cache writes take longer. This is normal. Measure average speed over a day, not per-request. Compare average times with and without caching. You’ll see the benefit.

Pitfall 3: Running Workflows Too Frequently

Every commit triggers everything. That’s 50-100 Claude runs per day per engineer.

What happens: $100+ per day for a 10-person team. $2,000+ per month.

Fix: Trigger on PR only. Run comprehensive checks nightly. You’ll save 80% and get better results (Claude has more time to think). Night runs can be thorough; day runs can be fast.

Pitfall 4: Using the Wrong Model

“We use Opus for everything because it’s the most capable.”

What happens: 10x the cost you need. $0.50 for a lint check instead of $0.05.

Fix: Haiku for 80% of tasks. Sonnet for code review. Opus never in CI. Be ruthless about model selection.

Pitfall 5: No Monitoring

You get your Anthropic bill and it’s $5,000 higher than expected.

What happens: You scramble to figure out which workflows are the culprit. By then you’ve burned through your budget.

Fix: Log token usage per workflow. Set budget alerts. Review metrics weekly. A spreadsheet with daily token counts prevents surprises.

Real-World Cost Savings Examples

Example 1: DevTools Team (Saved 78%)

Before optimization:

  • Workflow triggers on every push: 120 runs/day
  • Uses Opus for all tasks: $0.50 per run average
  • No caching, sends full codebase (50,000 tokens)
  • Daily cost: $60 | Monthly: $1,320 | Annual: $15,840

After optimization:

  • Triggers on PR only + nightly: 30 runs/day
  • Haiku for linting, Sonnet for reviews: $0.12 average per run
  • Caching style guides and examples: -40% token use
  • Daily cost: $13.20 | Monthly: $290 | Annual: $3,480

Savings: $12,360 per year (78% reduction)

This team did a full audit, implemented all 6 strategies, and achieved dramatic savings without sacrificing quality. Their nightly comprehensive scans (running Sonnet) catch issues their PR reviews (Haiku + Sonnet) miss.

Example 2: Documentation Team (Saved 85%)

Before:

  • Generates docs on every commit: 200 runs/day
  • Full codebase context: 25,000 tokens per run
  • Output caching not implemented
  • Daily cost: $150 | Monthly: $3,300 | Annual: $39,600

After:

  • Generates docs on demand + scheduled daily: 15 runs/day
  • Only changed files + cached examples: 8,000 tokens per run
  • Caches generated docs: reuse 90% of previous output
  • Daily cost: $9.00 | Monthly: $198 | Annual: $2,376

Savings: $37,224 per year (85% reduction)

This team cut token usage by 68% and run frequency by 93%. Their docs are actually better because they’re doing fewer, more thorough generation passes instead of shallow regeneration on every commit.

Monitoring and Continuous Optimization

Cost optimization isn’t a one-time thing. Here’s how to keep improving.

Weekly Review Checklist

  1. Check token usage: Did any workflow spike? Why?
  2. Review cache hit rates: Are we hitting cache, or missing?
  3. Scan for slow runs: Anything running 2-3x longer than normal?
  4. Validate output quality: Are cheaper models producing acceptable results?
  5. Track cost per task: Is each workflow staying on budget?

Monthly Deep Dives

  • Compare costs across teams/projects
  • Identify workflows that can trigger less frequently
  • Test switching tasks from Sonnet to Haiku
  • Review logs for failed attempts (wasted tokens)
  • Analyze token usage trends (are we getting better or worse?)

Build a Cost Dashboard

# metrics/token-usage.json (committed weekly)
{
  "week": "2026-03-16",
  "workflows":
    {
      "code-review":
        {
          "runs": 52,
          "avg_input_tokens": 7200,
          "avg_output_tokens": 1800,
          "cache_hit_rate": 0.78,
          "total_cost": 18.52,
        },
      "test-generation":
        {
          "runs": 38,
          "avg_input_tokens": 5100,
          "avg_output_tokens": 3500,
          "cache_hit_rate": 0.42,
          "total_cost": 22.14,
        },
    },
  "total_weekly_cost": 48.30,
  "projected_monthly": 193.20,
}

Share this in Slack weekly. Celebrate savings. Investigate spikes. Make it visible.

Dashboard value: Visibility drives accountability. When teams see costs, they optimize. Anonymous costs hide waste.

Wrapping Up: Maximum Intelligence, Minimum Cost

Claude Code in CI/CD is powerful. But power without cost discipline turns into an expensive habit. The strategies here—optimized prompts, strategic caching, model selection, budget alerts, and output caching—can cut your bill by 70-85% without sacrificing quality.

Start with the quick wins: trigger less frequently, use Haiku for simple tasks, implement prompt caching for static context. Then move to the advanced techniques: dynamic model selection, output caching, concurrent concurrency limits.

Most importantly: measure. You can’t optimize what you don’t see. Set up monitoring from day one, review weekly, and adjust continuously.

The teams saving the most money aren’t the ones who guessed best—they’re the ones who measured, experimented, and iterated. That’s the path to sustainable, cost-efficient AI automation in CI/CD. Start small, measure everything, iterate aggressively. Your future self will thank you when you’re not explaining a $10,000 API bill to your manager.


For more on Claude API pricing, rate limits, and optimization, check out the Pricing – Claude API Docs, Manage costs effectively – Claude Code Docs, and Claude Code: Rate limits, pricing, and alternatives.

—iNet

Free Discovery Call

Start With a Conversation, Not a Commitment

Every engagement begins with a free 30-minute discovery call. We'll map what's slowing your business down and tell you exactly what we'd fix first – no pitch deck, no obligation.