A demo only has to work once. A production integration has to keep working when the provider is slow, when a customer sends ten times the usual traffic, when a retrieval index returns the wrong document, and when a tool server is handed a hostile argument. This module covers the reliability and grounding half of that job. The recurring exam logic applies throughout: put anything that must always hold in code, prevent a failure instead of only detecting it, and change one variable at a time when you investigate.
The scenarios below use invented companies. API behaviour (status codes, headers, stop_reason) is taken from Anthropic's documentation, listed at the end. Where a number depends on your account or model, the lesson says to check the docs instead of quoting it.
2.1 Retry only what is transient
A retry is a bet that the same request will succeed later. That bet only makes sense when the failure was caused by a temporary condition.
| Signal | Meaning | Retry? |
|---|---|---|
429 rate_limit_error |
You exceeded a rate limit | Yes, after the wait the response asks for |
500 api_error, 504 timeout_error, 529 overloaded_error |
Server-side or capacity trouble | Yes, with backoff and a cap |
| Connection failure or client timeout | The response never arrived | Yes, but only if the call is safe to repeat |
400 invalid_request_error |
The request itself is wrong | No, fix the request |
401 authentication_error, 403 permission_error |
Credential or permission problem | No, fix the credential or access |
413 request_too_large |
Request exceeds the size limit | No, shrink the request |
Two details matter in production. First, when a response carries a retry-after header, wait that many seconds; the docs say earlier retries might fail. Second, not every 429 is a rate limit you can wait out. The docs describe a 429 for a reached monthly spend cap that never carries retry-after, and retrying it fails until access resumes. Look at the error body and cap your attempts rather than looping forever.
Use exponential backoff with jitter (a random component). Without jitter, every client that failed together retries together, and the synchronised wave causes the next failure.
Figure 1. Retry decision for one failed call
How to read this: start at the top and follow the question that matches your error code; the only loop is the dotted line, and it always passes through a wait and an attempt limit.
Picture it: A shop opens at nine and the door jams. If every locked-out customer tries again exactly one minute later, they all arrive together and jam it again. If each waits a slightly different, random time, the crowd spreads out and the door copes. Jitter is that random spread. (Unlike the shop, your clients cannot see each other, which is why the randomness has to be built in.)
import random
import time
import anthropic
client = anthropic.Anthropic(max_retries=0) # we own the retry policy here
def call_with_retry(make_request, max_attempts=4, base=0.5, cap=20.0):
for attempt in range(max_attempts):
try:
return make_request()
except anthropic.APIStatusError as e:
transient = e.status_code in (429, 500, 504, 529)
if not transient or attempt == max_attempts - 1:
raise # 400, 401, 403, 413 and exhausted retries surface
hint = e.response.headers.get("retry-after")
delay = float(hint) if hint else min(cap, base * 2 ** attempt)
time.sleep(delay + random.uniform(0, delay / 2))
The SDK already retries by default (the docs say up to two retries, and it honours retry-after and an x-should-retry header when present). That is why the example sets max_retries=0: stacking your own loop on top of the SDK's multiplies attempts, which turns a brief brownout into a retry storm. Pick one layer to own the policy.
On call, 3 a.m.: At Fernbank Travel, Priya Nair is paged because a short provider brownout has turned into a long one. Her service wraps each call in its own loop of four attempts, and the SDK underneath retries up to twice on top of that, so one failing request can become up to 12 calls. One hundred stuck requests become as many as 1,200 calls, all landing on a provider that is already struggling. She sets the SDK retries to zero, keeps her own capped loop with jitter, and the storm ends. Invented example.
Retrying is only safe when repeating the call has no side effect. A model call is safe to repeat. A tool that sends an email or charges a card is not, unless it carries an idempotency key.
Exam angle. A scenario shows a dashboard where retries hit 400 errors "until the budget runs out". The tempting fix is more backoff or a longer delay. The correct fix is to stop retrying non-transient errors at all. Common trap: treating "retry everything with backoff" as the safe default.
2.2 Rate limits, timeouts and long requests
Rate limits in the Claude API are enforced at the organization level; you can additionally set lower limits per workspace to protect one team from another. A second API key does not create more capacity. The limits are measured in requests, input tokens and output tokens per minute, and the docs say the algorithm is a token bucket, so capacity refills continuously rather than resetting on the minute. A burst can therefore trigger a 429 even when the per-minute average looks fine, and the docs also describe ramp limits that can reject a sharp jump in usage.
Cache reads help here. The docs state that cached input tokens read from the cache do not count toward the input-tokens-per-minute limit, while uncached input and cache writes do. Caching is a throughput lever as well as a cost lever (module 5).
On timeouts: a non-streaming request that runs for a long time can be dropped by a network device that closes idle connections. The docs recommend streaming or the Message Batches API for long-running requests, especially those over 10 minutes. A streaming response can also fail after the HTTP 200 has been sent, delivering an error event in the stream (for example overloaded_error). The SDK does not retry an error inside a stream, so your code must handle it and decide whether to discard the partial output and restart.
| Problem | Right lever |
|---|---|
| Sustained 429s at normal traffic | Request a limit increase, lower per-workspace limits for noisy tenants, cache stable prefixes |
| Burst of simultaneous jobs | Queue and smooth the rate; start bulk jobs gently |
| Request over 10 minutes, connection drops | Stream (or batch) instead of one long blocking call |
| Large non-urgent backlog | Batch API (module 5) |
Exam angle. "We get 429s, so we created extra API keys for each service." The limit is on the organization, so keys add nothing. Common trap: reading a per-key quota into a per-organization limit.
2.3 Circuit breakers, refusals and graceful degradation
A circuit breaker stops sending traffic to a dependency that is failing, so you fail fast and give it room to recover. The design question is what it should count.
Count infrastructure failures: timeouts, connection errors, 5xx, 529. Do not count successful calls whose content you dislike. A model that declines a request returns a normal HTTP 200 with stop_reason: "refusal" on models that use classifier refusals; the docs state it is a successful response, not an error. It is application logic: read stop_details, show the user an appropriate message, or route to a fallback path. If you counted refusals as failures, a burst of users asking out-of-policy questions would open the breaker and take down a healthy dependency. Equally, do not feed 400s and 401s into the breaker; those are bugs on your side, and tripping a breaker will not fix them.
Figure 2. The three states of a circuit breaker
How to read this: follow the loop Closed, Open, Half-open and back; the arrow that loops on Closed is the refusal case, which never moves the breaker.
Picture it: A fuse box. When a faulty appliance draws too much current, the fuse trips so the wiring does not burn, and the rest of the house keeps its power. The breaker in your code does the same for a failing dependency. (A household fuse needs a person to reset it; a software breaker tests the dependency with a few calls and resets itself.)
Two more facts about refusals. A refusal before any output is billed in some categories and not others, and it still counts against your rate limits. A refusal can also arrive mid-stream, in which case treat the partial output as incomplete and discard it.
Degrade deliberately. When the breaker is open, serve something useful: a cached answer, a shorter non-AI path, or a queue-and-notify flow. Mark it visibly (a "showing saved answer from 09:40" banner) so users and downstream systems know the result is not live. Silent staleness is worse than an honest error.
Act before the threshold. If the error rate climbs from 1% to 8% and the breaker opens at 50%, you serve eight failures in a hundred for as long as the climb lasts. Add early actions below the trip point: shed low-priority traffic, shorten timeouts, switch non-critical features to the degraded path.
Exam angle. A breaker opens each time a compliance question gets declined. The tempting fix is a higher threshold. The real fix is to stop counting 200-with-refusal responses as failures. Common trap: equating "the response was unhelpful" with "the service is down".
2.4 RAG: chunking, filtering and isolation
Retrieval-augmented generation fails mostly at retrieval, not at the model. Four design choices decide quality.
Structure-aware chunking. Splitting every N tokens cuts tables, price lists and schedules in half, so a chunk contains the row but not its column header. The model then confidently reads the wrong column. Chunk along document structure: keep a table or a schedule whole (repeat the header in each piece if it must be split), keep a heading with its section.
Metadata pre-filtering. Attach tenant, document version and effective date to each chunk and filter before the similarity search. Post-filtering takes the top k from everything and then discards results; if the top 10 were mostly another tenant's or an expired version, you are left with zero or two useful chunks and an apparently random answer.
{
"chunk_id": "pol-117#c4",
"tenant": "acme-travel",
"doc": "refund-policy",
"version": "2026-09",
"effective_from": "2026-09-01",
"supersedes": "2025-11",
"source_url": "https://docs.example.test/refund-policy"
}
Isolation. When separation is a regulatory requirement (health, financial, contractual), a metadata filter is a soft boundary: one missed filter leaks data. Use physical separation (separate indexes or databases per tenant) and per-session credentials, so the application cannot query another tenant even if it is manipulated. Prevent rather than detect.
Figure 3. Hard isolation: a credential that only opens one tenant's index
How to read this: follow the solid arrow to Tenant A's index; the red dashed arrow to Tenant B's index is blocked by the credential itself, not by a filter the application might forget.
Picture it: A hotel. A keycard that only opens your floor is a hard boundary. A note on the lift saying "please do not visit other floors" is a metadata filter: fine until one guest ignores it. When the rule is a legal requirement, build it into the lock.
Exam angle. Users of tenant A occasionally see tenant B's wording. The tempting fix is "tell the model not to mention other tenants". The correct fix is a hard filter or physical separation in the retrieval layer. Common trap: relying on the prompt to enforce data isolation.
2.5 Reranking, multi-facet retrieval and provenance
First-stage retrieval is fast and approximate. A reranker scores a small candidate set (say 30) against the query with a more expensive model and keeps the best few. Add it when the right chunk is usually in the candidates but not at the top. If the right chunk is never retrieved, reranking cannot help; fix chunking, filters or the query instead. Diagnose by checking recall at k before adding components.
Multi-facet queries. "Compare the cancellation terms for the premium plan with the data export rules" is two questions. One embedding of the combined text tends to land between them and retrieves neither well. Decompose the query into sub-queries, retrieve for each, and merge.
Provenance and superseded sources. Every chunk should say where it came from and whether it is still current. When a policy is replaced, mark the old document superseded (or exclude it by effective date) rather than hoping the newer one outranks it; two contradictory chunks in the context make the answer a coin flip. Return source references to users so they can check.
| Symptom | Likely layer |
|---|---|
| Correct chunk exists but ranks 18th | Add or tune a reranker |
| Answer mixes old and new policy | Superseding and effective-date filter |
| Cross-topic question answered half-way | Multi-facet retrieval |
| Table value attributed to the wrong column | Chunking |
2.6 Grounding: verify after generation
Instructing the model to "only use the provided documents" lowers the rate of unsupported claims; it does not make it zero. Production grounding adds a check in code after generation.
- Have the model return claims with the chunk ids and exact quotes that support them.
- Verify in code that each quote actually occurs in the cited chunk, and that the cited chunk was one that you retrieved for this user.
- Drop or flag any claim that fails; if too many fail, return a "could not verify" answer or escalate.
Figure 4. Verify claims in code after the model answers