Lesson 14 Cost, Caching & Rate Limits
Theme:
Lesson 14 · Slide 1

Cost, Caching & Rate Limits

Production LLM applications must manage costs, leverage caching for efficiency, handle rate limits gracefully, and use the Batch API for high-volume workloads. This lesson covers the economics and operational patterns of Claude at scale.

Learning Objectives

Lesson 14 · Slide 2

Token Pricing

Claude uses per-token pricing with separate rates for input and output tokens.

ModelInput (per MTok)Output (per MTok)
Claude Opus 4$15$75
Claude Sonnet 4$3$15
Claude Haiku 3.5$0.80$4

MTok = million tokens. Output tokens cost 5× more than input tokens because generation is more compute-intensive than processing input.

Key insight: A long system prompt read many times is expensive. If 2,000 tokens of system prompt are sent 1,000 times with Sonnet, that is 2M input tokens = $6. With caching, the same cost drops to ~$0.60.

Lesson 14 · Slide 3

Prompt Caching

Prompt caching lets you cache frequently reused prefixes (system prompts, long documents, tool definitions) so you pay a reduced rate on subsequent requests.

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system=[{
        "type": "text",
        "text": LONG_SYSTEM_PROMPT,      # 2000+ tokens
        "cache_control": {"type": "ephemeral"}
    }],
    messages=[{"role": "user", "content": "Hello!"}]
)

Pricing with Cache

  • Cache write: 25% more than base input price (first request only)
  • Cache read: 90% less than base input price (subsequent requests)
  • Cache TTL: 5 minutes (resets on each cache hit)
Lesson 14 · Slide 4

Cache TTL & Gotchas

Important rules for prompt caching:

Common Gotchas

  • Dynamic timestamps in system prompts invalidate the cache every time
  • Tool definitions count toward the cache prefix — put them before dynamic content
  • Reordering messages breaks the prefix match
  • Cache is per-model: switching between Sonnet and Haiku means separate caches
Lesson 14 · Slide 5

Batch API

For workloads that do not need real-time responses, the Batch API offers 50% cost savings with a 24-hour SLA.

batch = client.messages.batches.create(
    requests=[
        {
            "custom_id": f"task-{i}",
            "params": {
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": task}],
            }
        }
        for i, task in enumerate(tasks)
    ]
)
print(f"Batch ID: {batch.id}")  # Poll for results

Use cases: Classification of large datasets, generating summaries for a document collection, evaluating model outputs, bulk data extraction. Any workload where you can afford to wait hours, not seconds.

Lesson 14 · Slide 6

Rate Limits

Claude enforces rate limits at two levels:

Limit TypeWhat It MeasuresTypical Tier 1
Requests per minute (RPM)Number of API calls50 RPM
Tokens per minute (TPM)Total input + output tokens40,000 TPM
Tokens per day (TPD)Daily token budget1,000,000 TPD

When you hit a limit, the API returns 429 Too Many Requests with a retry-after header.

import time

def call_with_backoff(fn, max_retries=5):
    for attempt in range(max_retries):
        try:
            return fn()
        except anthropic.RateLimitError as e:
            wait = 2 ** attempt  # 1, 2, 4, 8, 16 seconds
            print(f"Rate limited. Waiting {wait}s...")
            time.sleep(wait)
    raise Exception("Max retries exceeded")
Lesson 14 · Slide 7

Demo

Live demonstration: prompt caching savings and batch API usage.

Demo Steps

  1. Send a request with a 2,000-token system prompt — observe cache_creation_input_tokens
  2. Send the same request again — observe cache_read_input_tokens
  3. Calculate cost savings: cache write vs cache read vs no cache
  4. Submit a batch of 10 tasks and poll for results
  5. Compare batch cost (50% discount) vs real-time cost
  6. Trigger a rate limit and show exponential backoff recovery
Notes: Show the response.usage object for each call. The cache hit/miss fields make the savings concrete and visible.
Lesson 14 · Slide 8

Lab & Homework

Lab Exercises

  1. Caching — send cached requests, measure token savings
  2. Budget Checker — build a token/cost estimator
  3. Batch API — submit 20 tasks and process results

Homework Tasks

  1. Audit an existing project for caching opportunities
  2. Build a budget checker that warns before exceeding limits
  3. Compare batch vs real-time: cost, latency, quality
1 / ?