CubeAPM
CubeAPM CubeAPM

How to Monitor Anthropic Claude API Usage and Token Spend: Step-by-Step Guide 2026

How to Monitor Anthropic Claude API Usage and Token Spend: Step-by-Step Guide 2026

Table of Contents

Without monitoring, a Claude API integration can silently burn through your budget during a traffic spike. A prompt misconfiguration that doubles token counts, a cache miss rate that climbs without warning, or a batch job that shifts to Priority tier without anyone noticing all of these show up as line items at month end, not as alerts when they happen. According to the 2024 State of AI Infrastructure Report, unmonitored AI workloads regularly exceed budgets by 40% or more, with token costs being the primary driver.

This guide walks through how to monitor Claude API usage and token spend using the Anthropic Analytics API, build cost tracking dashboards, set up threshold alerts, and integrate monitoring into your existing observability stack. You will know exactly how much you are spending, which workspaces or models are driving cost, and how to catch budget overruns before they hit your invoice.

Prerequisites

Before setting up Claude API monitoring, ensure you have the following:

  • An active Anthropic account with API access
  • Organization Admin or Developer role to create API keys and access the Analytics API
  • Access to the Anthropic Console for workspace and API key management
  • A monitoring or observability platform to store and visualize metrics (CubeAPM, Datadog, Grafana, Prometheus, or similar)
  • Basic familiarity with REST APIs and JSON response handling
  • Python 3.8+ or another language with HTTP client support if building custom monitoring scripts

Step 1: Understand the Anthropic Analytics API and What It Tracks

The Anthropic Analytics API provides detailed usage and cost data for Claude workloads. Unlike CloudWatch or generic application logs, this API surfaces token-level granularity across models, workspaces, service tiers, and API keys.

The Analytics API tracks:

  • Input and output token counts per model (Claude Opus 4, Claude Sonnet 3.5, Claude Haiku)
  • Service tier usage (Standard, Priority, Batch)
  • Cache performance (ephemeral tokens, cache reads, cache writes)
  • Code execution and web search activity
  • Cost per workspace and API key

Access the Analytics API documentation at https://docs.anthropic.com/en/api/usage-and-cost-api.

The API returns usage data in JSON format with daily granularity. Each response includes workspace IDs, model names, token counts, and associated costs. This level of detail allows you to answer questions like “which workspace consumed the most tokens yesterday?” or “did cache hit rates drop after the last deployment?”

Step 2: Generate an API Token for the Analytics API

To authenticate requests to the Analytics API, create a dedicated API token with Analytics read permissions.

Navigate to the Anthropic Console and log in. Go to Settings → API Keys and click Create API Key. Name the key something descriptive like analytics-monitoring-prod. Under Permissions, ensure Analytics Read is enabled. Copy the API key immediately — it will not be shown again.

Store the API key securely in your secrets manager (AWS Secrets Manager, HashiCorp Vault, or similar). Never hardcode API keys in application code or commit them to version control.

Test the API key with a curl request:

curl -H "x-api-key: YOUR_API_KEY" \
     -H "anthropic-version: 2023-06-01" \
     https://api.anthropic.com/v1/usage

A successful response returns usage data for your organization. If you receive a 401 Unauthorized error, verify the API key was copied correctly and that Analytics Read permissions are enabled.

Step 3: Query Usage and Cost Data via the Analytics API

The Analytics API supports queries for token usage, cost, and performance metrics across workspaces and time ranges.

Basic usage query to retrieve token counts for the last 7 days:

curl -X GET "https://api.anthropic.com/v1/usage?start_date=2026-01-01&end_date=2026-01-07" \
     -H "x-api-key: YOUR_API_KEY" \
     -H "anthropic-version: 2023-06-01"

Sample JSON response:

{
  "usage": [
    {
      "date": "2026-01-01",
      "workspace_id": "ws-abc123",
      "model": "claude-opus-4",
      "service_tier": "standard",
      "input_tokens": 1500000,
      "output_tokens": 300000,
      "cache_reads": 50000,
      "cost_usd": 42.50
    }
  ]
}

Query parameters you can use:

  • start_date and end_date — date range in YYYY-MM-DD format
  • workspace_id — filter by specific workspace
  • model — filter by model name (e.g., claude-opus-4, claude-sonnet-3.5)
  • service_tier — filter by Standard, Priority, or Batch

Group usage by workspace to identify which teams are driving the highest costs:

curl -X GET "https://api.anthropic.com/v1/usage?start_date=2026-01-01&end_date=2026-01-07&group_by=workspace_id" \
     -H "x-api-key: YOUR_API_KEY" \
     -H "anthropic-version: 2023-06-01"

This returns aggregated token counts and costs per workspace, making it easy to spot outliers.

Step 4: Build a Token Usage Dashboard

Once you have usage data from the Analytics API, visualize it in a dashboard to track trends over time. This step assumes you are using an infrastructure monitoring platform like CubeAPM, Grafana, or Datadog.

For CubeAPM users, ingest Analytics API responses as custom metrics using the OpenTelemetry Collector. Configure the collector to poll the Analytics API every hour and send metrics to CubeAPM:

receivers:
  prometheus:
    config:
      scrape_configs:
        - job_name: 'claude-usage'
          scrape_interval: 1h
          static_configs:
            - targets: ['api.anthropic.com']
          metrics_path: /v1/usage
          params:
            start_date: ['2026-01-01']
            end_date: ['2026-01-07']
          headers:
            x-api-key: YOUR_API_KEY
            anthropic-version: 2023-06-01
processors:
  batch:
exporters:
  otlp:
    endpoint: cubeapm-collector:4317
service:
  pipelines:
    metrics:
      receivers: [prometheus]
      processors: [batch]
      exporters: [otlp]

In CubeAPM, create a dashboard with the following panels:

  • Total token usage over time — line graph showing daily input + output tokens
  • Cost by workspace — bar chart grouping cost by workspace ID
  • Cache hit rate — percentage of cache reads vs. total tokens
  • Service tier distribution — pie chart showing Standard vs. Priority vs. Batch usage
  • Top 5 models by cost — table ranking Claude Opus, Sonnet, and Haiku by spend

For Grafana users, write a Python script to poll the Analytics API and expose metrics in Prometheus format. Use the prometheus_client library:

from prometheus_client import start_http_server, Gauge
import requests
import time
token_usage = Gauge('claude_token_usage', 'Claude API token usage', ['workspace', 'model'])
cost_usd = Gauge('claude_cost_usd', 'Claude API cost in USD', ['workspace'])
def fetch_usage():
    response = requests.get(
        'https://api.anthropic.com/v1/usage',
        headers={
            'x-api-key': 'YOUR_API_KEY',
            'anthropic-version': '2023-06-01'
        },
        params={'start_date': '2026-01-01', 'end_date': '2026-01-07'}
    )
    data = response.json()
    for entry in data['usage']:
        token_usage.labels(
            workspace=entry['workspace_id'],
            model=entry['model']
        ).set(entry['input_tokens'] + entry['output_tokens'])
        cost_usd.labels(workspace=entry['workspace_id']).set(entry['cost_usd'])
if __name__ == '__main__':
    start_http_server(8000)
    while True:
        fetch_usage()
        time.sleep(3600)

Run this script on a server accessible to your Prometheus instance. Configure Prometheus to scrape http://your-server:8000/metrics. Build Grafana dashboards using the claude_token_usage and claude_cost_usd metrics.

Step 5: Set Up Cost and Usage Alerts

Dashboards show trends, but alerts catch problems before they compound. Set threshold-based alerts for token usage spikes, cost overruns, and cache performance degradation.

In CubeAPM, navigate to Alerts → Create Alert. Configure a token usage spike alert:

  • Metric: claude_token_usage
  • Condition: sum(rate(claude_token_usage[1h])) > 500000
  • Alert message: “Claude token usage exceeded 500k tokens/hour in workspace {{workspace}}”
  • Route to: Slack, PagerDuty, or email

Set a cost threshold alert to catch budget overruns:

  • Metric: claude_cost_usd
  • Condition: sum(claude_cost_usd) > 1000
  • Alert message: “Claude API costs exceeded $1,000 threshold”
  • Route to: Finance team via email, engineering Slack channel

Configure a cache hit rate alert to detect performance degradation:

  • Metric: claude_cache_reads / (claude_cache_reads + claude_input_tokens)
  • Condition: cache_hit_rate < 0.40
  • Alert message: “Claude cache hit rate dropped below 40% — check prompt configurations”
  • Route to: DevOps on-call

For Prometheus and Grafana users, define alerting rules in Prometheus:

groups:
  - name: claude_alerts
    rules:
      - alert: HighTokenUsage
        expr: sum(rate(claude_token_usage[1h])) > 500000
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Claude token usage spike detected"
          description: "Token usage exceeded 500k/hour in workspace {{ $labels.workspace }}"
      - alert: CostThresholdExceeded
        expr: sum(claude_cost_usd) > 1000
        for: 10m
        labels:
          severity: critical
        annotations:
          summary: "Claude API costs exceeded budget"
          description: "Total cost: ${{ $value }}"

Reload Prometheus configuration and verify alerts trigger correctly by simulating high usage in a test workspace.

Step 6: Track Service Tier and Model Distribution

Claude offers three service tiers — Standard, Priority, and Batch — each with different pricing and performance characteristics. Monitoring which tier your workloads use prevents unexpected cost spikes.

Query the Analytics API grouped by service tier:

curl -X GET "https://api.anthropic.com/v1/usage?start_date=2026-01-01&end_date=2026-01-07&group_by=service_tier" \
     -H "x-api-key: YOUR_API_KEY" \
     -H "anthropic-version: 2023-06-01"

Add a service tier breakdown panel to your dashboard showing Standard vs. Priority vs. Batch usage as a stacked area chart. This visualization surfaces shifts in workload priority that might drive cost changes.

Similarly, track model distribution to understand whether your team is using Claude Opus (most expensive), Claude Sonnet (balanced), or Claude Haiku (cheapest) for different workloads. Query by model:

curl -X GET "https://api.anthropic.com/v1/usage?start_date=2026-01-01&end_date=2026-01-07&group_by=model" \
     -H "x-api-key: YOUR_API_KEY" \
     -H "anthropic-version: 2023-06-01"

Create a table ranking models by cost and token volume. If Opus dominates spend but most prompts could run on Sonnet, this becomes an optimization opportunity.

Step 7: Integrate Claude Monitoring with Your Observability Stack

If you already use an observability platform for APM, logs, and infrastructure metrics, integrate Claude usage data into the same system to correlate API costs with application behavior.

For CubeAPM users, Claude usage metrics ingested via OpenTelemetry automatically appear alongside application traces, logs, and infrastructure metrics. Link a Claude token spike to a specific API endpoint by correlating the timestamp of the spike with APM traces showing increased request volume to that endpoint.

For Datadog users, follow the Anthropic integration guide. Configure the integration by adding your Anthropic API key in the Datadog app under Integrations → Anthropic. Datadog automatically ingests token counts, costs, and cache metrics. Create a unified dashboard showing Claude costs alongside infrastructure spend (EC2, RDS, Lambda) to understand total cloud cost per service.

For Elastic Stack users, write a Logstash pipeline to ingest Analytics API responses:

input {
  http_poller {
    urls => {
      claude_usage => {
        url => "https://api.anthropic.com/v1/usage?start_date=2026-01-01&end_date=2026-01-07"
        headers => {
          "x-api-key" => "YOUR_API_KEY"
          "anthropic-version" => "2023-06-01"
        }
      }
    }
    schedule => { cron => "0 * * * *" }
    codec => "json"
  }
}
output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "claude-usage-%{+YYYY.MM.dd}"
  }
}

Visualize Claude usage in Kibana using the claude-usage-* index pattern. Correlate token spikes with application logs showing increased prompt sizes or failed requests.

Step 8: Optimize Token Usage Based on Monitoring Data

Once monitoring is in place, use the data to identify optimization opportunities. Three common patterns surface in most Claude deployments:

Cache misses driving up input token costs. If cache read percentage drops below 40%, prompt variations or ephemeral session tokens are bypassing the cache. Review prompt templates for unnecessary dynamic content that invalidates cache keys. A single extra line of context that changes on every request can double input token costs.

Workspaces using Priority tier when Standard would suffice. Priority tier costs more but delivers faster responses. If monitoring shows a non-critical workspace using Priority, switch it to Standard and measure whether the latency difference affects user experience. For batch processing jobs, Batch tier cuts costs significantly with delayed response times.

Model selection mismatched to task complexity. If Claude Opus handles simple classification tasks that Claude Haiku could do faster and cheaper, you are overpaying. Use monitoring data to audit which models each workspace uses. Run A/B tests to validate whether Sonnet or Haiku deliver acceptable results for specific use cases currently running on Opus.

For infrastructure monitoring platforms that track application performance alongside AI costs, link token usage to specific API endpoints. If one endpoint drives 60% of Claude spend, optimize the prompt logic or cache strategy for that endpoint first.

Troubleshooting Common Issues

Analytics API returns 401 Unauthorized. Verify the API key was copied correctly and includes Analytics Read permissions. Check that the x-api-key header is set in all requests. If the key was recently created, wait 5 minutes for propagation across Anthropic’s systems.

Usage data does not match invoice totals. The Analytics API provides near-real-time data but invoices reflect finalized usage after month end. Small discrepancies (1-2%) are normal due to rounding and processing delays. For significant differences, compare cost_usd totals in API responses against line items in the Anthropic Console billing page.

Cache hit rate metrics are missing. Cache performance metrics (cache_reads, cache_writes) only appear if prompt caching is enabled and used. Verify your API requests include the cache_control parameter. Check that prompts are structured to reuse cached content across requests.

Dashboard shows no data after setup. Confirm the Analytics API returns data when queried manually via curl. Check that your monitoring platform’s collector or scraper is running and has network access to api.anthropic.com. Review logs for HTTP errors or authentication failures.

Alerts fire too frequently or not at all. Tune alert thresholds based on baseline usage. If alerts fire hourly, increase the threshold or extend the evaluation window. If alerts never fire, verify the alert condition matches the metric name and aggregation function used in your monitoring platform.

Token counts seem inconsistent across workspaces. Different workspaces may use different models or service tiers, which affects token counting. Verify you are grouping by workspace and model when comparing usage. Check whether prompt templates vary across workspaces — longer prompts naturally consume more tokens.

Monitor Anthropic Claude API Usage with CubeAPM

CubeAPM provides native monitoring for Claude API usage alongside APM, logs, infrastructure, and Cassandra monitoring tools in a single platform. Ingest Analytics API metrics via OpenTelemetry, visualize token consumption and costs in real time dashboards, and set threshold alerts for budget overruns. CubeAPM runs on-premises or in your VPC, keeping telemetry data inside your infrastructure with no external dependencies. Pricing is $0.15/GB of data ingested with unlimited retention and no per-seat fees. Teams using CubeAPM report 60-75% lower monitoring costs compared to SaaS platforms while maintaining full observability across all layers of their stack.

Learn more about what is infrastructure monitoring and how it integrates with AI API cost tracking, or explore synthetic monitoring to test Claude API endpoints from multiple global locations.

Anthropic Claude API monitoring is not a one time setup. Token usage patterns shift as your application scales, new features launch, and prompt strategies evolve. Set a recurring calendar reminder to review your Claude dashboard monthly. Look for workspaces with rising costs, models being used for the wrong tasks, and cache hit rates trending downward. These patterns catch cost overruns early and turn monitoring from reactive alerts into proactive optimization.

Disclaimer: The information in this article reflects the latest details available at the time of publication and may change as technologies and products evolve. Features, pricing, and plan limits can change over time. Always verify the latest information directly with the vendor before making purchasing or deployment decisions.

Frequently Asked Questions

How do I access the Anthropic Analytics API?

Generate an API key with Analytics Read permissions in the Anthropic Console under Settings → API Keys. Use the key in the `x-api-key` header when making requests to `https://api.anthropic.com/v1/usage`.

What is the difference between input tokens and output tokens in Claude billing?

Input tokens are the tokens in your prompt sent to Claude. Output tokens are the tokens Claude generates in its response. Output tokens typically cost more per token than input tokens. Cache reads reduce input token costs when reusing previously processed content.

How often does the Analytics API update usage data?

The Analytics API provides near-real-time data with a delay of approximately 15 minutes. Daily aggregates become available at midnight UTC. For sub-hourly monitoring, poll the API every 10-15 minutes.

Can I track Claude API usage per user or API key?

Yes. Group usage by `api_key_id` in Analytics API queries to see per-key consumption. This helps identify which services or teams are driving the highest costs. Workspace-level grouping provides broader organizational visibility.

What is prompt caching and how does it reduce token costs?

Prompt caching stores frequently reused prompt sections so Claude does not reprocess them on every request. Cache reads cost significantly less than processing new input tokens. Enable caching by structuring prompts with static sections that repeat across requests.

How do I monitor Claude API rate limits?

The Anthropic Console Usage page shows current rate limit headroom. The Analytics API does not expose rate limit metrics directly. Monitor request latency and HTTP 429 rate limit errors in your application logs to detect when you approach limits.

What monitoring tools integrate with the Anthropic Analytics API?

CubeAPM, Datadog, Grafana, Prometheus, Elastic Stack, and custom scripts using Python or Node can ingest Analytics API data. Any platform that supports REST API polling and JSON parsing can monitor Claude usage.

×
×