RBRunbook
Study

Domains · Domain 2 · 20% of scored questions

Production Integration, Reliability, and Knowledge Grounding

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
SignalMeaningResponse
400 invalid_request_errorThe 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-afterA rate limit (requests, input tokens, output tokens) or a ramp limitWait at least that long, then retry. Smooth the traffic.
429 with no retry-afterThe tier's monthly spend cap was reachedStop retrying. It fails until access resumes or the cap is raised.
500 api_error, 529 overloaded_errorTransient platform-side failure; a 529 reflects traffic across all usersRetry 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
  1. Retry only retriable outcomes. Permanent errors never succeed on retry.
  2. Use randomised exponential backoff and honour retry-after.
  3. Retry at one layer. Three layers that each retry three times turn one failure into 27 calls.
  4. Cap retries per request and add a process-wide retry budget, so a dependency outage produces some failed requests and not a retry storm.
  5. 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 limitTypical evidenceLevers that work
RPMMany small requests; bursts at the top of a minuteSmooth with a client-side queue or token bucket; combine small calls
ITPMLarge repeated prefixes, low cache hit ratePrompt caching (cache reads do not count toward ITPM); trim context
OTPMLong generationsShorter outputs; move non-urgent generation to batch
Ramp limit429s while well under every per-minute limit, right after a jump in trafficStart 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:

  1. 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.
  2. 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.

  1. 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.
  2. 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.
  3. Return tools in a deterministic order so clients and prompt caches stay stable.
  4. 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.

  1. Audit which keys and services call the old model (usage export by API key and model).
  2. 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.
  3. Run the regression suite against the new model in every platform configuration you run in production. Re-baseline cost and latency.
  4. 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
SituationStart with
The whole corpus fits comfortably in the context windowPut it in the prompt and cache it. No retrieval pipeline.
Large, fairly static corpus; tight latency budgetPre-computed retrieval (RAG): index once, look up fast.
Content that changes constantly, or questions that need several hopsAgentic search: give the model search tools and let it explore at run time.
Mostly static with some exploration neededHybrid: 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
  1. 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.
  2. 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.
  3. 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.
EvidenceLikely stageFix
Queries with exact identifiers, codes or rare terms fail; paraphrased queries workSearch: embeddings aloneHybrid 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 lostPrepend chunk-specific context before embedding and lexical indexing; revisit chunk boundaries
Right chunk is retrieved but ranked lowRankingRerank a wide candidate set down to a short list
Right chunk in context, answer contradicts or goes beyond itGenerationGrounding instructions, citations, permission to decline
Recall collapses after an embedding model changeIndexRe-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

Sample questions

Sample question
A retail support assistant streams replies to a chat widget. The trace for one turn reads:
message_start        model=primary
content_block_delta  "To reset the device you first need to..." (41 tokens)
message_delta        stop_reason=refusal  category=general_harms
The widget had already rendered the 41 tokens. The handler then saved them to the conversation history and to the CRM ticket as the assistant's answer, and the next turn was sent with that text included. The team wants the handling of this stop reason to match its documented behaviour. Which change should they make?
  • AKeep the partial text as the final answer and append a notice that the reply was cut short
  • BResend the same request to the same model with exponential backoff until the turn completes
  • CRemove the partial text from the widget and history, then retry the turn on a fallback model
  • DKeep the partial text in history and send a new user turn that asks the model to continue it
Show the answer and explanation

Answer:

  • Remove the partial text from the widget and history, then retry the turn on a fallback model

A refusal can arrive mid-stream after some output, and the documentation says to treat that partial output as incomplete and discard it; the usual way to still get an answer is to retry on another model. Asking the model to continue keeps declined content in the conversation and builds on it. Appending a cut-short notice is the handling for a token-limit truncation, where the partial text is still valid content. Backoff retries are for transient errors; a classifier decline on the same model and input is not a transient failure.

Sample question
A logistics company moves a nightly address-normalisation job of 90,000 requests from synchronous calls to the Message Batches API. The request builder is new code written for the batch job. The first production batch is created without error and shows in_progress. Three hours later it ends with:
request_counts: succeeded 0, errored 90000, canceled 0, expired 0
result.error.type: invalid_request_error   (same message on every line)
The team wants to stop losing a night's run to this failure shape. What should they add to the pipeline first?
  • AA polling step that checks the batch status every minute and cancels batches that run long
  • BA pre-flight step that sends one request of each shape through the synchronous Messages API
  • CA retry step that resubmits every errored request in a fresh batch with the same parameters
  • DA splitting step that divides the nightly job into smaller batches of ten thousand requests
Show the answer and explanation

Answer:

  • A pre-flight step that sends one request of each shape through the synchronous Messages API

Batch creation does not validate each request's parameters; validation errors are reported only when the whole batch has finished, so a malformed request shape costs hours. Sending a sample of each shape through the synchronous Messages API surfaces the same validation error in seconds. Resubmitting identical parameters reproduces the same error. Polling and cancelling shortens nothing, because the error is only visible in the results. Smaller batches fail in the same way, just in more pieces.

Sample question
A fintech's statement-analysis service sends a pinned API version header and a pinned model ID, and has run unchanged for months. On Tuesday, with no deploy on the team's side, stream workers begin to crash:
event: (a name that appears in no earlier log)
data: {...}
ValueError: unhandled event type
  at stream_parser.dispatch(event)
The name now appears on about one stream in five. Non-streaming calls from the same service still succeed. Product notes that the version header was already pinned and asks how to prevent this class of outage. Which change most directly addresses it?
  • APin the SDK and HTTP client versions in the service's build file
  • BSend an older API version header on every request from the service
  • CSwitch the affected calls from streaming to non-streaming requests
  • DMake the parser skip and log any event type that it does not recognise
Show the answer and explanation

Answer:

  • Make the parser skip and log any event type that it does not recognise

Within a single API version, existing inputs and outputs are preserved, but new optional fields and new variants of enum-like outputs such as streaming event types may be added. The trace shows exactly that: an event name the client has never seen, with nothing changed on the team's side. A client therefore has to tolerate values it does not know. An older version header gives the same guarantee and no stronger one. The crash is in the team's own dispatch code reacting to new server output, so pinning client libraries changes nothing. Non-streaming responses can gain new enumerated values in the same way, for example a new stop reason, and long requests lose the protection streaming gives them.

Sample question
A government records office answers staff questions over council meeting transcripts. Each transcript is sent as one plain text document with citations enabled. Reviewers say the citations point to real text but are hard to use:
Claim: "The motion passed 5-2."
  cited_text: "Aye."       (chars 18812-18816)
  cited_text: "Carried."   (chars 19340-19348)
Auditors require every citation to cover one whole speaker turn, including the speaker's name. The source files already mark where each turn starts and ends. Which change most directly meets the requirement?
  • ASend each transcript as a custom content document with one content block per speaker turn
  • BSend each transcript as a PDF document so that each citation reports a page range instead
  • CAdd a system prompt rule that tells the model to cite only complete speaker turns by name
  • DTurn citations off and ask the model to quote each relevant speaker turn inside its answer
Show the answer and explanation

Answer:

  • Send each transcript as a custom content document with one content block per speaker turn

Plain text and PDF documents are chunked into sentences, and a sentence is the smallest unit a citation can cover, which is why single-word sentences are cited. A custom content document is not chunked further: the blocks you supply are the citable units, so one block per speaker turn gives exactly the required granularity. A PDF is still sentence-chunked and only adds page numbers. A prompt rule cannot change the unit the API cites. Prompt-based quoting gives up the guarantee that cited text is a real span of the source.

↑↓ move↵ openesc close