About 12 of the 60 scored questions come from this domain. It has 4 skills:
Lessons
Skill
Reliability Engineering for Claude Services
Classify the failure before you retry, fall back, or degrade
Most reliability mistakes in a Claude integration come from treating every bad outcome as the same event. The first decision is always: what kind of outcome is this? Only then pick a response. There are two separate channels to read.
Channel 1: HTTP errors
| Signal | Meaning | Response |
|---|
400 invalid_request_error | The request is wrong (bad parameter, prompt too long, a spend limit you set yourself) | Do not retry. Fix the request or the limit. |
429 with retry-after | A rate limit (requests, input tokens, output tokens) or a ramp limit | Wait at least that long, then retry. Smooth the traffic. |
429 with no retry-after | The tier's monthly spend cap was reached | Stop retrying. It fails until access resumes or the cap is raised. |
500 api_error, 529 overloaded_error | Transient platform-side failure; a 529 reflects traffic across all users | Retry with jittered exponential backoff, inside a budget. A higher quota does not help. |
The error body tells limits apart: on the Messages API error.details.error_code distinguishes a spend cap and a ramp limit from an ordinary rate limit. Branch on that code and on typed SDK exceptions, not on message text.
Channel 2: stop reasons on a successful response
A stop reason arrives with HTTP 200. Error handlers never see it, so your code has to read stop_reason on every response.
max_tokens: the output is truncated. If a tool call was cut off, retry with a higher limit.model_context_window_exceeded: the context filled up. Treat the output as truncated and reduce the context; a bigger output limit does nothing.pause_turn: a server-tool loop paused. Send the assistant content back unchanged to continue.refusal: a safety classifier declined. Discard any partial output. Retrying the same model is pointless; retry on another model, or change the prompt when the category is about exposing reasoning.
A cross-model fallback wired only to refusals does not protect you from overload, and a retry wrapper wired only to 5xx never sees a refusal. Server-side fallback is triggered by a classifier decline only; rate limits, overload and server errors on the requested model come back to you as-is.
Retry design
- Retry only retriable outcomes. Permanent errors never succeed on retry.
- Use randomised exponential backoff and honour
retry-after. - Retry at one layer. Three layers that each retry three times turn one failure into 27 calls.
- Cap retries per request and add a process-wide retry budget, so a dependency outage produces some failed requests and not a retry storm.
- Remember the SDK already retries transient failures a small number of times. Count that layer.
Circuit breakers and graceful degradation
When the failure rate stays high, stop sending: open the circuit, serve a degraded response (a cached answer, a smaller model, a queue-and-notify path), and probe for recovery with a little traffic. Degradation should reduce work, be decided by request criticality (shed background work before interactive work), and be exercised regularly, because a path that is never used usually does not work.
Fallbacks and feature parity
Cross-region and cross-platform fallbacks only help if the fallback can run the same request. Platforms do not all offer the same features: for example, the Bedrock endpoint that serves the Messages API does not support server-side tools, the MCP connector, or Message Batches. Before relying on a fallback route, list every feature the primary request uses (server tools, beta headers, batch, fallback parameters) and check each feature page's availability section for the target platform. Where a feature is missing, build the degraded path on purpose: client-side tools in place of server tools, the SDK's client-side fallback in place of the server-side one. Size the fallback model's rate limits for the traffic it will receive; a fallback that is itself rate limited returns the original refusal.
Test the fallback under real traffic shape before the incident. A fallback first exercised during an outage is a second outage.
Sources
Claude API errors
Rate limits
Stop reasons and fallback
Refusals and fallback
Claude in Amazon Bedrock (bedrock-mantle)
SRE book: Addressing Cascading Failures
SRE book: Handling Overload
Skill
Scale and Throughput Management
Find the binding constraint: requests, input tokens, output tokens, or batch economics
Throughput problems look alike from the outside: 429s, growing queues, late jobs. The fix depends on which limit is actually binding, so measure before changing anything.
Read the limit, do not guess it
Messages API rate limits are measured per model class in requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). The 429 body says which limit was exceeded, and response headers report the limit, the remaining amount and the reset time for requests, input tokens and output tokens. Put those three remaining values on a dashboard. The one closest to zero at peak is your constraint.
| Binding limit | Typical evidence | Levers that work |
|---|
| RPM | Many small requests; bursts at the top of a minute | Smooth with a client-side queue or token bucket; combine small calls |
| ITPM | Large repeated prefixes, low cache hit rate | Prompt caching (cache reads do not count toward ITPM); trim context |
| OTPM | Long generations | Shorter outputs; move non-urgent generation to batch |
| Ramp limit | 429s while well under every per-minute limit, right after a jump in traffic | Start low and step up; spread scheduled jobs evenly |
- Limits use a token bucket that refills continuously. A per-minute limit can be enforced over shorter intervals, so 200 requests in two seconds can fail even when the minute average is low.
- Only uncached input and cache writes count toward ITPM. Raising the cache hit rate on a shared prefix raises effective throughput without a limit increase.
- OTPM counts tokens actually generated.
max_tokens is not reserved against it, so lowering max_tokens below what you already generate frees nothing. - A spend cap also returns 429 but has no
retry-after; it is a budget problem, not a throughput problem.
Asking for a higher limit is slow and does not fix shape problems. A burst, a missing cache breakpoint, or a noisy tenant will consume the new limit as well.
Queueing and backpressure
A queue in front of the API turns bursts into a steady rate, but an unbounded queue only hides overload. Bound the queue, attach a deadline to each item, drop work whose caller has already timed out, and push back on producers (reject early, or slow intake) when the queue is full. Give interactive traffic priority over background traffic.
Multi-tenant isolation
Organisation limits are shared. Two layers isolate tenants:
- Workspaces for a small number of workload classes. Each workspace can carry its own spend and rate limits per limiter type, which protects the others. Organisation-wide limits still apply even if workspace limits add up to more.
- Application-level budgets for many tenants: a token budget per tenant per minute and a fair queue, so one tenant's bulk job cannot starve the rest.
Batch pipelines
The Message Batches API trades latency for price: half the standard price, asynchronous, usually done within an hour but allowed up to 24 hours, after which unprocessed requests expire. It has its own limits and is not subject to ramp limits. Use it when nobody is waiting for the answer.
- Validation is asynchronous. Dry-run one request of each shape through the Messages API first.
- Results arrive in any order. Match on
custom_id. - Each request ends as succeeded, errored, canceled or expired. Handle each type and resubmit by
custom_id; one failure does not affect the others. - Streaming, fast mode and server-side fallback parameters are not accepted in a batch.
- Batch is not available on every platform. Check before designing a fallback around it.
Capacity planning
Forecast peak tokens per minute, not daily totals: requests per minute times average uncached input and output per request, with headroom. Compare against each limit, decide which one binds first, and act on that one. Ramp traffic up before a launch and request limit increases ahead of time.
Sources
Rate limits
Batch processing
Claude API errors
SRE book: Addressing Cascading Failures
SRE book: Handling Overload
Skill
Production MCP and Change Management
Operate MCP servers, model versions and prompts as versioned, reversible changes
Three things change underneath a production Claude system: the tools (often MCP servers), the model, and the prompt. Each needs a version, a test before release, a staged rollout and a way back.
Remote MCP: deployment and authentication
- The Messages API MCP connector reaches servers over HTTP at an
https:// URL. A local stdio server cannot be attached directly; host it behind an HTTP transport or run your own MCP client. - The connector takes an OAuth access token per server. Your application runs the OAuth flow and refreshes the token; the API does not.
- An MCP server is an OAuth resource server. It validates each token and must only accept tokens issued for itself. Forwarding the caller's token to a downstream API (token passthrough) is forbidden: get a separate downstream credential.
- No valid token returns 401. A valid token without the needed scope returns 403 with an
insufficient_scope challenge, and the client does a step-up authorisation with limited retries. - Limit exposure with toolset configuration: allowlist the tools an agent needs, or denylist write and destructive tools for a read-only assistant.
- Third-party servers are not operated or endorsed by Anthropic. Connect only to servers you trust.
Tool and schema versioning
A tool's name, description and input schema are part of the prompt. Changing them changes model behaviour and invalidates prompt caches.
- Make additive changes (new optional parameter, new tool). For a breaking change, publish a new tool name or version and keep the old one for a deprecation window.
- An MCP server can change its tool list at any time. Pin the tool list you tested where the platform allows it, and review changes before adopting them.
- Return tools in a deterministic order so clients and prompt caches stay stable.
- Report input and business errors as tool execution errors with actionable text, so the model can correct itself. Keep protocol errors for malformed requests and unknown tools.
Model migrations
A model ID is a pinned snapshot. It does not upgrade itself, and it retires on a published date, after which requests fail. Retirement dates on partner-operated platforms can differ from Anthropic-operated ones, so track each platform separately.
- Audit which keys and services call the old model (usage export by API key and model).
- Read the migration guide for your starting model. New models can reject parameters the old one accepted and can change the response shape, for example a response that starts with a thinking block breaks code that reads the first content block as text.
- Run the regression suite against the new model in every platform configuration you run in production. Re-baseline cost and latency.
- Canary, compare, then shift traffic. Keep the old model configured until the new one is proven.
Pinning the API version header does not freeze the response format. Within a version, new optional fields and new enum values (stop reasons, streaming event types) can appear. Parsers must ignore what they do not recognise.
Prompt versioning and progressive rollout
Treat the prompt, model ID, tool schemas and parameters as one immutable, versioned release unit stored in source control. Never edit a live prompt in place. Release through an evaluation gate, then a small canary with guardrail metrics and automatic rollback, then wider traffic. Rollback means pointing traffic back at the previous version, which only works if that version still exists unchanged. Managed agent configurations are versioned by the platform; for Messages API prompts you build this yourself.
Gateways and configuration parity
A gateway centralises credentials, budgets, audit logs and provider switching, but it becomes infrastructure you operate: a gateway that does not forward new headers or fields silently disables the features that depend on them. Keep a per-platform parity table (model IDs, beta headers, features, limits) and test each route in CI.
Sources
MCP connector
Remote MCP servers
Understanding Authorization in MCP
MCP Security Best Practices
MCP Versioning
MCP specification: Tools
Model deprecations
Model IDs and versioning
Claude Sonnet 5.5 migration guide
API versions
Define your agent
Other LLM gateways
Skill
Retrieval and Knowledge Grounding at Scale
Choose the retrieval architecture, then debug it one stage at a time
A knowledge-grounded answer passes through stages: the corpus is chunked and indexed, candidates are retrieved, candidates are ranked and cut to a short list, and the model generates from that list. A wrong answer can come from any stage. Fixing the wrong stage is the most common waste of effort.
Pick the architecture first
| Situation | Start with |
|---|
| The whole corpus fits comfortably in the context window | Put it in the prompt and cache it. No retrieval pipeline. |
| Large, fairly static corpus; tight latency budget | Pre-computed retrieval (RAG): index once, look up fast. |
| Content that changes constantly, or questions that need several hops | Agentic search: give the model search tools and let it explore at run time. |
| Mostly static with some exploration needed | Hybrid: retrieve some context up front, allow further tool-driven search. |
The trade-off is direct. Run-time exploration avoids stale indexes and handles multi-step questions, but it is slower than looking up pre-computed data and uses more tokens. Pre-computed retrieval is fast and cheap per query, but the index must be kept fresh and a single lookup can miss.
Stage-by-stage diagnosis
- Is the supporting passage in the candidate set? Measure recall at the candidate depth on a labelled set. If not, the problem is chunking, embedding or search.
- Is it in the short list the model sees? If recall is high at depth 150 but low at depth 5, the problem is ranking. Add a reranker or pass more chunks.
- Given the right passage, is the answer right? Test generation with the gold passage supplied. If it still fails, the problem is the prompt or grounding, not retrieval.
| Evidence | Likely stage | Fix |
|---|
| Queries with exact identifiers, codes or rare terms fail; paraphrased queries work | Search: embeddings alone | Hybrid search: add lexical (BM25) results and fuse the rankings |
| Retrieved chunk is from the wrong entity or period; chunk text says "the company", "this quarter" | Chunking: context lost | Prepend chunk-specific context before embedding and lexical indexing; revisit chunk boundaries |
| Right chunk is retrieved but ranked low | Ranking | Rerank a wide candidate set down to a short list |
| Right chunk in context, answer contradicts or goes beyond it | Generation | Grounding instructions, citations, permission to decline |
| Recall collapses after an embedding model change | Index | Re-embed the whole corpus; queries and documents must share a model. Build the new index beside the old one and switch. |
Reranking cannot recover a passage that was never retrieved, and a better embedding model cannot fix a chunk that has lost its subject. Find the stage first.
Reranking adds a run-time step, so it costs latency and money in exchange for precision. Passing more chunks raises the chance the answer is present but can distract the model. Tune both on your own evaluation set.
Grounding practices
- Citations. The API citations feature returns the cited source text itself and guarantees each citation points at a real span of a supplied document. Prompt-based quoting has no such guarantee. Default chunking is by sentence; custom content documents let you define the citable unit.
- Your own search results. Pass retrieved passages as search result blocks with a source and title so each citation carries them.
- Structured output. Citations cannot be combined with schema-constrained output. Ask for one field per line, parse in code, and check that every field has a value and a citation.
- Uncertainty. Give the model explicit permission to say it does not know, restrict it to the supplied documents, and have it retract any claim it cannot support with a quote.
- Confidence signals. Use observable signals: whether a claim has a citation, retrieval scores, and agreement across repeated runs. Route low-confidence answers to a fallback or a human.
Sources
Contextual retrieval in AI systems
Effective context engineering for AI agents
Embeddings
Citations
Search results
Reduce hallucinations