Skip to content

Lesson 17 ยท The Claude API

Streaming, Errors, Caching and Batches

Make Claude API apps reliable and affordable: stream long replies, handle error codes and retries, reuse prompts with caching and process bulk work in batches.

A script that works once is a start. A real application must cope with slow replies, temporary failures and growing bills. This lesson covers four tools for that.

Streaming

With streaming, you receive the answer in pieces as it is produced. Users see progress sooner, and long requests are less likely to hit network timeouts.

Python
with client.messages.stream(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": "Write a study plan for SQL."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    final = stream.get_final_message()

print("\n", final.stop_reason)

Check stop_reason on the final message. An error can also arrive after the stream has started successfully, and the SDK does not retry an error inside a stream, so decide what your app does with a partial answer.

Errors

Status Type Typical response
400 invalid_request_error Fix the request; a spend limit you set can also cause it
401 authentication_error Check the key
402 billing_error Check billing
403 permission_error Check access
413 request_too_large Send less
429 rate_limit_error Wait and slow down; spend caps can also cause it
500 api_error Retry with limits
529 overloaded_error Retry later

This is not the complete list. The official SDKs retry some failures twice by default, including connection errors, timeouts, 408, 409, 429 and server errors, and they follow the server's retry hints. Set max_retries on the client to change this. Be careful about adding a second retry loop on top, because the attempts multiply.

Python
import anthropic

client = anthropic.Anthropic(max_retries=3)

try:
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=1000,
        messages=[{"role": "user", "content": "Hello"}],
    )
except anthropic.RateLimitError:
    print("Rate limited. Try again later.")
except anthropic.APIConnectionError:
    print("Network problem.")
except anthropic.APIStatusError as error:
    print("API error", error.status_code)

Responses carry a request ID. Log it, because support can use it to trace a call. Do not log API keys or user content that you do not need.

If you call the HTTP API without an SDK, retry only suitable errors, wait longer each time, and stop after a few attempts.

Python Stand-in: retry with exponential backoff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The small random addition, called jitter, stops many clients from retrying at the same instant. Real code should obey a retry-after header when the server sends one.

Prompt caching

If many requests start with the same long content, such as instructions or a manual, prompt caching lets the API reuse the processed prefix. The prefix is built in the order tools, system, then messages. Matching requires an identical prefix.

Python
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=1000,
    system=[{
        "type": "text",
        "text": LONG_STABLE_MANUAL,
        "cache_control": {"type": "ephemeral"},
    }],
    messages=[{"role": "user", "content": question}],
)
print(response.usage.cache_creation_input_tokens,
      response.usage.cache_read_input_tokens)

You can instead put cache_control at the top level of the request for automatic caching of a growing conversation. Facts as of December 2026:

  • The default lifetime is 5 minutes, and a 1-hour option exists.
  • Writing costs more than normal input: 1.25 times for 5 minutes, 2 times for 1 hour.
  • Reading costs much less: usually 0.1 times the base input price, and 0.05 times for Opus 5.5 and Sonnet 5.5. Some other models differ.
  • Prompts below a minimum size are not cached, without any error. It is 512 tokens for the 5.5 models.

Put stable content first and changing content, such as the date or the user's question, after the breakpoint. If cache reads stay at zero, look for something that changes in the prefix. input_tokens counts only the uncached part, so add the two cache fields to get the total input.

Message Batches

For work that does not need an immediate answer, such as labeling thousands of records, the Message Batches API processes requests asynchronously at 50% of the standard price.

Python
batch = client.messages.batches.create(requests=[
    {"custom_id": "review-1", "params": {
        "model": "claude-opus-5-5", "max_tokens": 500,
        "messages": [{"role": "user", "content": "Label this review: ..."}]}},
])
print(batch.id, batch.processing_status)

According to the documentation, most batches finish within an hour, a batch expires if it is not done within 24 hours, and results stay available for 29 days after creation. One batch holds up to 100,000 requests or 256 MB. Each result is succeeded, errored, canceled or expired. Match results to inputs by custom_id, not by their position.

Python Stand-in: match batch results by custom_id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Design for failure

Decide in advance what your application does when a call fails after all retries. Good options include showing a clear message with a retry button, saving the job to a queue for later, or falling back to a manual process. Be careful with retries when a request leads to an action. If your program already ran a tool, for example created an order, a blind retry of the whole workflow could create a second one. Record what has been done, and make actions safe to repeat where you can.

Watch a few numbers over time: error rate by type, latency, tokens per request, cache read share and cut-off responses. A sudden change often points to a new input pattern or a change in your own code.

Respect rate limits

The API limits how fast your organization can send requests and use tokens, and the limits depend on your usage tier. Spread bulk work over time, limit how many calls run in parallel and increase traffic gradually, because a sharp rise can also cause errors. For large jobs that can wait, a batch is often simpler than building your own queue. The rate limit documentation and your Console show the current values for your account.

Common mistake: putting a timestamp at the top of the system prompt and then wondering why caching never helps. Every request then has a different prefix.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which error should you generally not retry unchanged?

    A bad key stays bad until you fix it.
  2. 2. What must be true for a cache hit?

    Caching works on identical prefixes.
  3. 3. How should batch results be matched to inputs?

    Do not rely on order.
  4. 4. When is a batch a good fit?

    Batches trade immediate answers for a lower price.

Summary

  • Stream long replies, and handle errors that occur mid-stream.
  • Know which errors to retry, and remember the SDK's own retries.
  • Cache stable prefixes and check the cache usage fields.
  • Use batches for work that can wait, and match results by ID.

Next: Structured Outputs: Reliable JSON from Claude

Your progress is saved in this browser. No account needed.