About six months ago, our engineering organization went from experimenting with Claude Code to making it part of everyday work. Just over three months, our AI spend grew about 275%. But without proper observability, we had almost no idea where that spend was going. All we had was a monthly cloud invoice. We couldn't attribute costs to a team, repository, model, or session. We couldn't show engineers their own usage. And we couldn't tell whether the money was going to something useful, something misconfigured, or an engineer's broken loop running overnight.
So, we did what we do best. We made Claude Code observable. We instrumented it like any other production system and sent the telemetry to New Relic. That observability gave us what we needed to optimize. A few months later, we'd cut our cost per million tokens by 71% and daily spend by 51%, all while token volume went up by 72%, with no measurable hit to output quality.
Cost per million tokens fell by more than half between May and November
Monthly token volume kept climbing between May and November, with cache reads making up the bulk of it.
The same telemetry that helped us cut costs also shows us which tools and skills engineers actually use. Our security team looks at a different part of it, the tool call events and their inputs and outputs, to spot signs of misuse. This post walks through how we set it all up, from instrumenting Claude Code to the alerts and changes that brought our costs down.
Sending Claude Code telemetry to New Relic with OpenTelemetry
Claude Code natively supports OpenTelemetry and emits metrics, logs, and traces out of the box. If you don't already know about OpenTelemetry (OTel), it is a vendor-neutral open standard for instrumenting and exporting telemetry data, and New Relic offers first-class support for OpenTelemetry across the platform. That's what makes the setup so simple. You point Claude Code at our OTLP endpoint with a handful of environment variables, and the data starts flowing. We roll out a small configuration organization-wide through Claude Code's managed settings. It turns telemetry on, sends metrics, logs, and traces over OTLP to New Relic, and sets what gets recorded along the way. Here's the example config block:
{
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"OTEL_SERVICE_NAME": "claude-code",
"OTEL_METRICS_EXPORTER": "otlp",
"OTEL_LOGS_EXPORTER": "otlp",
"OTEL_TRACES_EXPORTER": "otlp",
"OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
"OTEL_EXPORTER_OTLP_ENDPOINT": "https://otlp.nr-data.net:4317",
"OTEL_LOG_TOOL_DETAILS": "1",
"OTEL_LOG_USER_PROMPTS": "0",
"OTEL_METRICS_INCLUDE_ENTRYPOINT": "1"
}
}
The top section handles basic OTLP setup exporting metrics, logs, and traces to New Relic over gRPC. OTEL_LOG_TOOL_DETAILS=1 adds the names of the tools, MCP servers, and skills engineers invoke, which is how we can tell the plugins people actually use from the ones that just sit idle. The same data is also shared with our security team, who use it to make sure AI is used safely and responsibly across the organization.
Claude Code's own telemetry is only half the picture though. Our internal gateway handles all Claude traffic at New Relic, so we instrument it directly, before requests reach the model provider. For every request, the gateway records an OpenAICompletion custom event through the New Relic Python agent. The event carries token usage from the provider's response and cache writes split by cache duration (5-minute vs. 1-hour). It also carries the cost of each cache component, priced from the same rate table that enforces user spend limits. Finally, it records two timings and attributes the request to the team, app, user, and budget key behind it. Prompts and model responses are stripped before the event leaves the gateway. This proxy-layer instrumentation gives us visibility into data standard OTLP doesn't capture, such as internal budget attribution and cache durations. And because the gateway measures time to first token (TTFT) itself, we can tell whether a latency increase that clients see comes from our gateway or from the LLM provider.
Tracking Claude Code cost, usage, and code quality
Once the telemetry is flowing, we track it the same way on each of the three surfaces engineers use (the Claude Code CLI, Claude Code Desktop, and Claude Cowork). Every surface gets the same charts for active users, token usage, sessions, active time, lines of code, cost per user, requests by client version, and tool decisions. Keeping them identical means a number on one surface can always be compared like for like with another, and engineers can filter any of them down to their own email to check what they're spending. Most of what we track on each surface comes from six metrics that Claude Code exports over OTLP:
claude_code.cost.usage
claude_code.token.usage FACET type (input | output | cacheRead | cacheCreation)
claude_code.active_time.total FACET terminal.type
claude_code.session.count
claude_code.lines_of_code.count
claude_code.code_edit_tool.decision FACET tool_name, decision
Together, these six metrics cover cost, token usage, active time, sessions, lines of code, and whether engineers accept or reject the edits Claude Code proposes. We use FACET to break a metric down by one of its attributes, for example splitting token usage by type and edit decisions by tool and outcome. From these six metrics, we can see how much Claude Code costs and how widely engineers use it.
Cost
For cost, the metric we rely on most is token usage split into input, output, cache creation, and cache read. Total token count on its own tells you nearly nothing, because a session that reads ten million tokens from cache and a session that reprocesses ten million fresh look identical until you split them. However, they differ in price by roughly 10x. Cache hit rate falls out of that split:
cacheRead / (cacheRead + cacheWrite + input)
We aim for a hit rate of around 95%, and anything below 90% tells us something is causing the cache to miss and is worth investigating. Ours now holds at about 97%.
To find setups where the cache isn't working, or where something else is driving up cost, we compare active hours, cache hit rate, cost, and cost per active hour across the org. We sort the results by cost per active hour rather than total cost, because heavy usage on its own isn't something we need to fix. A setup that costs far more per hour than the norm usually points to a misconfiguration, like caching turned off or too many MCP servers loaded, and that's what we reach out to help with.
Usage
We track active users, sessions, active time, lines of code, and requests by client version on every surface, which tells us how widely Claude Code has been adopted across the org and how much engineers rely on it day to day.
Code Quality
Cost and usage tell us how much engineers use Claude Code and how efficiently, but not whether the code it writes is any good. For that, we track claude_code.code_edit_tool.decision, which records whether the engineer accepted or rejected each edit Claude Code proposed. It's what we check when someone asks whether a change like a cheaper default model made the assistant worse. In the screenshots here, more than 98% of edits and writes were accepted on every surface.
Tracking MCP tool calls, errors, and adoption
Since every MCP server an engineer loads adds tokens to each turn, we track which servers and skills are actually being used and which ones are just sitting in context. That data comes from OTLP logs rather than metrics, because Claude Code records each tool call and skill activation as a structured event. We query those events with NRQL, New Relic's query language, as follows:
-- which MCP tools are actually being called, and which ones fail
FROM Log SELECT count(*) AS 'Calls',
filter(count(*), WHERE success = 'false') AS 'Errors',
uniqueCount(username) AS 'Users'
WHERE service.name = 'claude-code' AND `event.name` = 'tool_result'
AND (tool_name LIKE 'mcp__%' OR tool_name = 'mcp_tool')
FACET mcpServer, mcpTool SINCE 7 days ago
-- which skills fire, and where they came from
FROM Log SELECT count(*) WHERE service.name = 'claude-code'
AND `event.name` = 'skill_activated' FACET skill.name SINCE 7 days ago
The first query above filters to tool_result events for MCP tools and, for each server and tool, counts the calls, the calls that failed, and the unique users behind them. The second filters to skill_activated events and counts how often each skill was activated, and both look back over the past seven days.
This is what turns "your context is too big" from an assertion into a ranked list of what's filling up the context window. Every MCP server you have installed costs tokens on every turn whether or not it gets called, so a ranked table of servers by call count next to the list of servers people have loaded is a direct readout of waste.. Our own New Relic MCP server tops it, and execute_nrql_query is the most-called tool (no surprises there). We also track error rates per MCP server and per tool, which caught more than one server that was failing half its calls and being retried.
The same data helps us decide which tools are worth keeping. For every skill and MCP server, we track activations and unique users over time, the same way we'd track adoption of any internal product. If nobody is using a tool, we retire it. If a tool's adoption is growing but so is its error rate, we treat it as a bug and fix it before more people run into it.
Using adoption data to curate our skill marketplace
Alongside the skills in our internal marketplace, engineers write plenty of their own, and some of them end up being used across whole teams. To find those, we use the same skill activation events from the second query above, which also record the plugin each skill came from. When there's no plugin (plugin.name is null), the skill was installed from outside our internal marketplace. In the screenshot above, the user skills chart ranks these skills by usage, with code-review well ahead of the rest. A skill that spreads across teams this way has already proven useful, so we use this list to decide which skills to package and publish to the marketplace for everyone.
Reducing MCP overhead by 57% in Claude Code sessions
When we looked at how many MCP tools each session loads, we found that most sessions started with a large block of MCP tool definitions, which get resent on every turn of the conversation. Rather than ask everyone to audit their own setup, we updated our gateway to support Claude Code's tool search. Instead of loading every tool definition from every configured MCP server into context on turn one, the model searches for and loads a tool's definition only when it's about to call it. It needed a change on our side of the wire, not just a client update, and it cut the median fixed overhead per session by 57%.
Setting up Claude Code alerts for cost and reliability
A dashboard only helps when someone is looking at it, so we set up alerts that tell us as soon as something goes wrong:
- Cache hit rate: This alert fires when the cache hit rate drops below 90% or falls to zero, which usually means caching is disabled, misconfigured, or split across accounts. Because cache reads are roughly 10x cheaper than fresh input, it's the alert that protects the cost the most.
- P95 time to first token: A latency spike for a model usually points to a slow model provider rather than our gateway. When that happens, we steer the org away from the affected models or regions.
- Server-side error rate: A spike in errors for a model or region points to an upstream failure. Several times, this alert flagged a Bedrock degradation before AWS's status page did.
- MCP server error rate: When an MCP server starts failing a large share of its calls, those calls get retried, which burns tokens and leaves engineers waiting.
The latency and error alerts work best together. When P95 time to first token rises but error rates stay flat, the model provider is usually just slow. When error rates rise but time to first token stays flat, something upstream is usually failing. Faceting both by model and region tells us whether the problem is one model, one region, or everything, and because our gateway measures both, we usually know before a public status page does.
How we cut Claude Code costs without limiting usage
Once we could see where the money was going, most of it traced back to two things, how well prompts were being cached and how much context each session carried. The five changes below target those two, and we rolled them all out centrally, so no engineer had to change anything themselves:
- Disabled cross-account invocation: Our deployment standards spread workloads across multiple cloud accounts for security and reliability, and our LLM gateway followed the same rule. The catch was that prompt caching is scoped per account, so when identical prompts landed in different accounts, they never found each other's cache. We noticed it when staging, which runs in a single account, kept showing a higher cache hit rate than production even though the code and the engineers were the same. Once we routed all of the gateway's requests through one account, the cache started doing its job.
- Raised the cache TTL from 5 minutes to 1 hour: A short meeting or a code review is easily long enough for a five-minute cache to expire before an engineer comes back to their session. With a one-hour TTL, the cache stays warm through those breaks.
- Enforced caching for all users: Caching was on by default, but some setups had it turned off, so we enforced it for everyone instead of chasing down each one.
- Set the org-wide soft default model to our mid-tier model: A lot of everyday coding work doesn't need our most capable model, so we made the mid-tier model the default. It's a soft default, which means engineers can still switch to a bigger model when a task needs it, and plenty do.
- Added tool search support to the gateway: This is the change we covered earlier, where the model loads an MCP tool's definition only when it's about to call it. It cut the median fixed overhead per session by 57%.
Measuring the impact on cost, usage, and code quality
To check that the changes actually worked, we compared two matched windows of ten weekdays each, one before any of them and one after all five were in place. Between the two windows, cost per million tokens dropped by 71% and daily cost by 51%. Over the same stretch, the cache read rate rose from 79% to 97% and token volume went up by 72%. Because token volume rose while daily cost fell, we know the result is a real efficiency gain and not a chilling effect from people using Claude Code less. Active users grew only 9% over the same period, so most of that extra volume comes from engineers doing more work with it. Commit and PR throughput also kept climbing, and we track the accept-versus-reject rate on code edits so that a change like a cheaper default model can be challenged with data rather than argued about.
Bonus: How telemetry helped us retire models and catch bad releases
We set up this telemetry to understand cost, but it has also made a few operational decisions much easier, like retiring old models, catching bad client releases, and asking for more capacity.
- Retiring deprecated models: Before setting a date, we queried thirty days of gateway traffic for each model we planned to retire. Almost all of it came from an automated PR review bot our own team owned, plus a handful of engineers. We fixed our bot, gave those engineers a week's notice, and shipped with nothing escalated, which saved us a month-long migration program.
- Catching bad client releases: Claude Code ships on two release channels, latest and stable, and a latest build sometimes brings a breaking change or new errors from a beta feature. We default the org to stable, and because every event carries the client version, we chart error rate by version. That tells us quickly whether a problem is in the Claude Code client, in our gateway, or in a new model whose request schema we don't support yet.
- Getting our rate limit raised: Our provider-side rate limit was throttling us at peak, which reached engineers as inference timeouts. Because our request was based on measured peak consumption rather than growth estimates, we got our quota raised faster than we would have otherwise. None of these needed any extra instrumentation, since the data was already there for cost tracking. It also turned out to be useful well beyond engineering.
Monitoring Claude Code for prompt injection, abuse, and data leaks
Our security team uses the same event stream to watch for a different set of risks. They look for prompt injection, where a tool result such as a fetched web page or a ticket description tries to steer the model into actions the engineer didn't ask for. They also watch for abuse, like unusual tool invocation patterns or a spike in usage from a single credential, and for PII or secrets showing up in tool inputs or outputs. If you're building this for your own AI features rather than for internal tool usage like ours, this is close to what New Relic AI Monitoring is built to give you out of the box. You get cost, quality, and safety signals over your LLM traffic without hand-rolling every query above yourself.
What's next
Claude Code's native OTLP export covers cost, usage, and quality across the org, but it doesn't show what happens inside a session. That's what we're adding next with Preflight, an open-source project from New Relic that captures every tool call, scores how efficiently the assistant worked, and flags anti-patterns like re-reading files or getting stuck in a loop. If you want to try this yourself, everything in this post works with a free New Relic account. Point Claude Code at New Relic using the config above, and you can start building your own queries and alerts straight away.
이 블로그에 표현된 견해는 저자의 견해이며 반드시 New Relic의 견해를 반영하는 것은 아닙니다. 저자가 제공하는 모든 솔루션은 환경에 따라 다르며 New Relic에서 제공하는 상용 솔루션이나 지원의 일부가 아닙니다. 이 블로그 게시물과 관련된 질문 및 지원이 필요한 경우 Explorers Hub(support.newrelic.com)에서만 참여하십시오. 이 블로그에는 타사 사이트의 콘텐츠에 대한 링크가 포함될 수 있습니다. 이러한 링크를 제공함으로써 New Relic은 해당 사이트에서 사용할 수 있는 정보, 보기 또는 제품을 채택, 보증, 승인 또는 보증하지 않습니다.