Production Patterns
Master observability, monitoring, and deployment patterns for production use.
What You’ll Learn
So far you have used Claude Code as a personal tool — one developer in a terminal. But Claude Code can also run headless in CI/CD pipelines, serve entire teams, and operate as part of automated workflows. Moving to production requires the same rigor as any production system: monitoring, testing, error handling, and cost control.
By the end of this session, you’ll understand:
- Headless mode for non-interactive automation
- CI/CD integration with GitHub Actions
- Observability: logs, OpenTelemetry metrics and events, and alerts
- Cost tracking and budgeting
- Testing agent workflows before they reach production
- The maturity model for scaling AI-assisted development
The Problem
A tool that works on your laptop is not the same as a tool that runs reliably in production:
Development: Production:
One user Many users/triggers
Interactive terminal Headless, no UI
Errors → you see them Errors → silent failure
Cost → your API bill Cost → team/org budget
Testing → "it worked for me" Testing → automated validation
Monitoring → you're watching Monitoring → dashboards + alerts
Every gap is a potential failure mode. This session covers how to close each one.
How It Works
Headless Mode
Claude Code runs without a terminal UI using the -p flag and structured output:
# One-shot mode with JSON output
claude -p "Summarize changes in the last 3 commits" --output-format json
# Pipe input for processing
cat requirements.txt | claude -p "Check for outdated dependencies"
# Reproducible scripted run: skip local hooks, plugins, MCP servers, and CLAUDE.md
claude --bare -p "Summarize README.md" --output-format json
The --output-format json flag is critical for automation. Instead of terminal output, you get one parseable result object (abridged):
{
"type": "result",
"subtype": "success",
"is_error": false,
"duration_ms": 4500,
"num_turns": 3,
"result": "Found 2 issues: ...",
"session_id": "4f0c…",
"total_cost_usd": 0.023,
"usage": { "…": "…" },
"modelUsage": { "claude-opus-5-5": { "…": "…" } }
}
total_cost_usd and the per-model modelUsage breakdown are client-side estimates, not your bill. When a run stops early, subtype names the reason, such as error_max_turns or error_max_budget_usd, and the object carries errors instead of result. Claude Code also exits with a non-zero code when a run fails, so scripts can branch on the exit status.
Two defaults matter in automation:
- Permissions. Since Claude Code 2.1.302, a
-prun with no permission mode set starts in Manual mode and denies any call that would need approval. Pre-approve what the job needs with--allowedTools, or make the lockdown explicit with--permission-mode dontAsk. - Configuration. Without
--bare,claude -ploads the hooks, MCP servers, skills, and CLAUDE.md it finds in the working directory and~/.claude, with no trust dialog.--bareskips that discovery so every machine gets the same run; on the Anthropic API it needsANTHROPIC_API_KEY(or anapiKeyHelper), because it never reads your subscription login.
CI/CD Integration
The most common production pattern: Claude Code in GitHub Actions.
# .github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
pull-requests: write
jobs:
review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Run AI Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
npm install -g @anthropic-ai/claude-code
git diff origin/main...HEAD | claude --bare -p \
"Review this diff for bugs and security issues." \
--output-format json \
--max-turns 20 \
--max-budget-usd 2 \
--permission-mode dontAsk \
> review.json || true
- name: Post Review Comment
if: always()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
let review;
try {
review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
} catch (e) {
review = { result: 'Review failed: ' + e.message };
}
const text = review.result ?? `Review stopped: ${review.subtype}`;
const cost = review.total_cost_usd ?? '?';
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## AI Code Review\n\n${text}\n\n---\nEstimated cost: \`$${cost}\``
});
Key production details:
timeout-minutes: 10— prevents runaway jobs--max-turns 20— caps agent iterations (print mode only)--max-budget-usd 2— stops the run once estimated spend reaches the cap; spend can pass it, so leave headroom--bare— the run ignores repository hooks, MCP servers, skills, and CLAUDE.md, so a pull request can’t add configuration that runs during the job--permission-mode dontAsk— anything not pre-approved is denied instead of waiting for a prompt|| trueandif: always()— a failed or capped run still posts a comment- stdout only — stderr is not redirected into
review.json, so warnings can’t corrupt the JSON
For teams that would rather not maintain this plumbing, Anthropic’s official anthropics/claude-code-action@v1 runs Claude Code in GitHub workflows: it answers @claude mentions, or runs a prompt --- plain text or a /skill-name --- with CLI flags such as --max-turns passed through claude_args. Team and Enterprise organizations can also turn on managed Code Review, which reviews pull requests without a workflow file.
Observability
┌──────────────────────────────────────────────────────┐
│ Layer 1: Logging │
│ What prompt, what tools called, what output, errors │
│ │
│ Layer 2: Metrics │
│ Tokens per session, cost per project, duration, │
│ tool call counts, error rates │
│ │
│ Layer 3: Alerting │
│ Cost exceeds threshold, error rate spikes, │
│ agent stuck in loop, unexpected tool calls │
└──────────────────────────────────────────────────────┘
Claude Code exports the first two layers itself through OpenTelemetry:
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp # metrics: cost, tokens, sessions
export OTEL_LOGS_EXPORTER=otlp # events: prompts, tool results, API errors
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
Useful signals include the claude_code.cost.usage and claude_code.token.usage metrics, which you can split by model and by skill.name or agent.name, plus events such as claude_code.tool_result and claude_code.api_error. Claude Code emits api_error only after its automatic retries are exhausted, so each one marks a request that really failed. Cost metrics are approximations; use your provider’s billing for invoices. Administrators can set these variables in managed settings, but a repository’s .claude/settings.json can’t turn telemetry on.
For one-off scripts, a simple cost tracking wrapper is enough:
#!/bin/bash
# track-cost.sh - log Claude Code cost per project
PROJECT="$1"; PROMPT="$2"
OUTPUT=$(claude -p "$PROMPT" --output-format json 2>/dev/null)
COST=$(echo "$OUTPUT" | jq -r '.total_cost_usd // 0')
MODELS=$(echo "$OUTPUT" | jq -r '(.modelUsage // {}) | keys | join("+")')
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "$TIMESTAMP,$PROJECT,$MODELS,$COST" >> "$HOME/claude-cost-log.csv"
echo "$OUTPUT" | jq -r '.result // ("stopped: " + .subtype)'
Cost Monitoring
┌──────────────────────────────────────────────────────┐
│ Layer 1: Per-run limits │
│ claude -p --max-budget-usd 5 --max-turns 20 │
│ │
│ Layer 2: Model and effort selection │
│ Haiku 5.5 for bulk work, Opus 5.5 or Fable 5.1 │
│ only where it pays off (prices: Session 21) │
│ │
│ Layer 3: Budget dashboards │
│ claude_code.cost.usage by project, developer, model │
│ │
│ Layer 4: Alerts │
│ "Project X spent $50 today (limit: $20)" │
└──────────────────────────────────────────────────────┘
Testing Agent Workflows
Agent workflows need testing just like code. Three levels:
┌──────────────────────────────────────────────────────┐
│ Agent Testing Pyramid │
│ │
│ E2E tests Full workflow in a test env │
│ "Does the review workflow │
│ produce a usable report?" │
│ │
│ Integration Skill + tools with a known │
│ tests prompt: "Does /team-review │
│ include a security section?" │
│ │
│ Unit tests Files and rules are well- │
│ formed: "Does every SKILL.md │
│ start with frontmatter?" │
└──────────────────────────────────────────────────────┘
Unit tests: Validate that skill files exist and are well-formed.
# Every skill folder needs a SKILL.md whose first line opens the frontmatter
for skill_dir in .claude/skills/*/; do
file="${skill_dir}SKILL.md"
if [ ! -s "$file" ]; then
echo "FAIL: missing or empty $file"; exit 1
fi
if [ "$(head -n 1 "$file")" != "---" ]; then
echo "FAIL: $file must start with --- frontmatter"; exit 1
fi
done
echo "PASS: all skill files present with frontmatter"
Integration tests: Run Claude Code with a known prompt and verify the expected behavior. User-invoked skills work in -p mode when the prompt starts with /skill-name:
OUTPUT=$(claude -p "/team-review" --output-format json 2>/dev/null)
if echo "$OUTPUT" | jq -r '.result // ""' | grep -q "Security Review"; then
echo "PASS: review skill produced a security section"
else
echo "FAIL: review skill missing security section"
fi
End-to-end tests: Run a complete workflow in a test environment and verify the outcome. If you ship skills and agents as a plugin, claude plugin eval runs a suite of realistic prompts against it and scores the results, so you can gate changes in CI.
The Maturity Model
Teams adopt Claude Code in stages, and each stage unlocks more value:
┌──────────────────────────────────────────────────────┐
│ Stage 1: Ad-hoc Usage │
│ Individual devs use Claude Code, no shared config │
│ → Personal productivity boost │
│ │
│ Stage 2: Personal Automation │
│ Own CLAUDE.md, personal skills, permission rules │
│ → Consistent personal workflows │
│ │
│ Stage 3: Team Standardization │
│ Shared CLAUDE.md, team skills and agents in │
│ .claude/, CI/CD reviews, per-project cost tracking │
│ → Team-wide consistency and quality │
│ │
│ Stage 4: Platform Integration │
│ All pipelines, custom MCP servers, OpenTelemetry │
│ dashboards, managed settings, plugins for sharing │
│ → Organizational capability │
└──────────────────────────────────────────────────────┘
Most teams are at Stage 1-2. Stage 3 is where the multiplier kicks in — shared knowledge means every team member benefits from the best workflows.
Key Insight
Production Claude Code is about reliability and predictability. The same principles that make software production-ready — monitoring, testing, error handling, cost management — apply directly to AI agent systems.
An agent that works 95% of the time on your laptop is not production-ready. Production-ready means:
- You know when it fails (monitoring)
- You know why it failed (logging)
- You know what it cost (budgeting)
- You know it behaves consistently (testing)
- You know it won’t do something unexpected (permissions)
The tools are not exotic — logs, metrics, alerts, tests, CI/CD. The only difference is that the “service” is an AI agent instead of a web server.
Hands-On Example
Combine everything into a production checklist for your first CI/CD integration:
1. Create .claude/skills/team-review/SKILL.md (review workflow, Session 23)
2. Create .claude/agents/security-reviewer.md (read-only security checks)
3. Run claude -p "/team-review" locally (the integration test above)
4. Add .github/workflows/ai-review.yml (the headless job above)
5. Store ANTHROPIC_API_KEY as a repository secret
6. Export OpenTelemetry metrics → alert on cost spikes
7. Review permission rules monthly → widen allow rules as trust builds
The CI job above reviews the raw diff with --bare, so it doesn’t load your skill. Once /team-review proves itself locally, move it into CI: either drop --bare and pass /team-review as the prompt, or use anthropics/claude-code-action@v1 with prompt: "/team-review" after actions/checkout. Either way the run now loads the repository’s skills, agents, hooks, and CLAUDE.md, so run it only on branches you trust.
Start with one pipeline. Measure quality and cost. Expand to more workflows as confidence grows. This is Stage 2 to Stage 3 in the maturity model — the transition from personal tool to team infrastructure.
What Changed
| Development Usage | Production Usage |
|---|---|
| Interactive terminal | Headless, JSON output |
| One developer | Team-wide, CI/CD triggers |
| Manual monitoring | OpenTelemetry dashboards and alerts |
| Cost is personal | Cost is capped, tracked, and budgeted |
| ”It works for me” | Automated validation |
| Ad-hoc workflows | Standardized skills, version-controlled |
| One session at a time | Many parallel sessions at scale |
Course Conclusion
You have completed the original core of the Claude Code Architecture Mastery course — the first 24 sessions across four modules (Module 5 continues below).
Module 1: Core Agent (Sessions 1-6) — The agent loop, tools and permissions, planning and task tracking, subagents and context isolation, skills and knowledge loading, context compaction. You learned that Claude Code is not a chatbot but an agent loop with tools, permissions, and context management.
Module 2: Multi-Agent (Sessions 7-12) — Task graphs, background tasks, agent teams, team protocols, autonomous agents, worktree isolation. You learned that complex work requires multiple agents coordinating through well-defined protocols.
Module 3: Real Architecture (Sessions 13-18) — Control protocols, MCP integration, hooks, session storage, CLAUDE.md design, permission models. You gained practical knowledge to configure, extend, and secure Claude Code.
Module 4: Mastery (Sessions 19-24) — Multi-CLI workflows, error recovery, cost optimization, human-in-the-loop, custom agents and skills, production patterns. You reached production readiness.
The Core Principles
Five ideas appeared across these first 24 sessions:
- The agent loop is the foundation. Tools, subagents, skills, teams — all built on: call API, check stop reason, execute tools, repeat.
- Context is the most precious resource. Subagents, compaction, skills, worktrees — every design decision manages context.
- Permissions are the safety net. Trust builds gradually, from restrictive to autonomous.
- Markdown is the extension language. No compilation, no deployment. Drop a file, gain a capability.
- Production requires production discipline. Monitoring, testing, error handling, cost management — familiar tools, new application.
Where to Go Next
- Build your skill library. Start with your team’s three most common workflows.
- Set up CI/CD integration. Start with automated PR reviews. Tune based on results.
- Contribute to the community. Share skills, agents, and patterns.
- Push the boundaries. Multi-agent architectures, custom MCP servers, novel coordination patterns.
You now have the architectural knowledge to build on top of Claude Code, not just use it. That is the difference between a user and a builder. Build something.
Continue to Module 5
The course originally ended here — but Claude Code did not stop evolving. The Claude 5 generation brought a new top model tier (Fable, now Fable 5.1 alongside Opus 5.5, Sonnet 5.5, and Haiku 5.5), effort levels and ultracode, scripted Workflow orchestration, persistent file-based memory, and scheduled autonomy.
Module 5: The Fable 5 Era covers all of it, starting with Session 25: The Claude 5 Family & Model Strategy.