Skip to content

    Certification

    CCDV-P M2: Production Integration, Reliability and Grounding

    Retry rules, rate limits, circuit breakers, refusals, RAG design, claim verification and MCP security for Claude apps that must stay up in production.

    By Published 30 min read

    Share

    This lesson is part of Claude Certified Developer — Professional. Enroll for free, then sign in, to read it in full.

    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.

    NOTE

    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

    flowchart TD accTitle: Retry decision for one failed call accDescr: A failed call is first classified. Non-transient failures such as 400, 401, 403 and 413 are not retried and the cause is fixed instead. Transient failures such as 429, 500, 504, 529 and timeouts lead to a check on whether repeating the call is safe. If it has a side effect and no idempotency key, it is not repeated blindly. If it is safe, the code checks whether attempts are left, then waits for the retry-after time or an exponential backoff with jitter, and calls again. With no attempts left the error is surfaced. A["Call failed"] B{"Is the failure transient?"} C["Do not retry: fix the request, credential or size"] D{"Safe to repeat?"} E{"Attempts left?"} F["Wait: retry-after, else backoff plus jitter"] G["Call again"] H["Surface the error"] I["Do not repeat without an idempotency key"] A --> B B -->|"400, 401, 403, 413"| C B -->|"429, 500, 504, 529, timeout"| D D -->|"no side effect, or key present"| E D -->|"side effect, no key"| I E -->|"yes"| F E -->|"no"| H F --> G G -.->|"fails again"| A

    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.

    TIP

    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.

    NOTE

    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.

    WARNING

    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

    stateDiagram-v2 accTitle: Circuit breaker states accDescr: The breaker starts closed and lets calls through. Too many infrastructure failures such as timeouts, connection errors, 5xx and 529 open it. While open it fails fast and the degraded path serves users. After a wait it becomes half open and lets a few test calls through. If they succeed it closes again, and if one fails it opens again. A refusal arrives as a successful 200 response, is handled by the application and never counts toward opening the breaker. state "Half-open" as HalfOpen [*] --> Closed Closed --> Open: too many infrastructure failures Open --> HalfOpen: after a wait HalfOpen --> Closed: test calls succeed HalfOpen --> Open: a test call fails Closed --> Closed: refusal handled by the app, not counted note right of Open Fail fast and serve the degraded path end note

    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.

    TIP

    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

    Per-tenant indexes with per-session credentialsTenant A user to Retrieval service (question); Retrieval service to Session credential (per session); Session credential to Tenant A index (allowed); Session credential to Tenant B index (denied)SEPARATE INDEX PER TENANTTenant A userTenant A userRetrieval serviceRetrievalserviceSession credential: tenant A onlySessioncredentialtenant A onlyTenant A indexTenant A indexTenant B indexTenant B indexquestionper sessionalloweddenied

    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.

    TIP

    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

    Claim verification after generationRetrieval to Model (question, chunks); Model to Claim verifier (claims, quotes); Claim verifier to Answer with sources (quote found); Claim verifier to Flag or escalate (no match); Retrieval to Retrieved chunks (keep a copy); Retrieved chunks to Claim verifier (check against)Retrieval: this user's chunksRetrievalthis user'schunksModel: claims plus quotesModelclaims plusquotesClaim verifier: code, not promptClaim verifiercode, not promptAnswer with sourcesAnswer withsourcesFlag or escalate: could not verifyFlag orescalatecould not verifyRetrieved chunks: the source textRetrievedchunksthe source textquestion, chunksclaims, quotesquote foundno matchkeep a copycheck against

    How to read this: the model's claims travel right to the verifier, which compares each quote with the saved source text; only claims that match reach the user, and the red path catches the rest.

    import re
    
    def norm(s: str) -> str:
        return re.sub(r"\s+", " ", s).strip().lower()
    
    def verify(claims, retrieved):
        """claims: [{"text", "chunk_id", "quote"}]; retrieved: {chunk_id: chunk_text}"""
        ok, bad = [], []
        for c in claims:
            source = retrieved.get(c["chunk_id"])
            if source is not None and norm(c["quote"]) in norm(source):
                ok.append(c)
            else:
                bad.append(c)
        return ok, bad

    This catches fabricated citations (a real-looking id with an invented quote) and citations to documents the user was never allowed to see. It does not prove the claim follows from the quote; for high-stakes answers add a second check or a human review step.

    Exam angle. A legal-research tool shows a citation to a clause that does not exist. The tempting fix is a stricter instruction or a lower temperature. The correct fix is verification of citations against the retrieved sources in code. Common trap: treating a prompt instruction as a verification mechanism.


    2.7 MCP in production

    A Model Context Protocol (MCP) server is a program the model's tool calls reach. In production it is an application like any other.

    Validate inputs. Tool arguments come from a model that may have read untrusted text. Validate types, ranges and formats with a schema, and reject rather than "fix" anything suspicious.

    Canonicalise paths. A file tool that accepts reports/../../etc/passwd or a symlink must resolve the path first and then check it sits under the allowed root.

    from pathlib import Path
    
    ROOT = Path("/srv/reports").resolve()
    
    def safe_path(user_path: str) -> Path:
        p = (ROOT / user_path).resolve()  # resolves .. and symlinks
        if not p.is_relative_to(ROOT):
            raise PermissionError("outside allowed directory")
        return p

    Scoped authorisation. For MCP servers reached over HTTP, the specification builds on OAuth. Points confirmed in the specification pages listed below:

    • A protected MCP server is an OAuth resource server and returns 401 with a WWW-Authenticate header so clients can discover how to authorise; 403 signals insufficient scope or permissions.
    • The server must check that an access token was issued specifically for it (the audience), and must reject tokens that were not.
    • Token passthrough is forbidden: the server must not forward the token it received to an upstream API. If it needs the upstream, it acts as a client there with a separate token.
    • Request narrow scopes, and elevate on demand; broad omnibus scopes enlarge the damage from a leaked token.

    The specification revision changes over time, so check the current page. Module 7 returns to token exchange and least privilege.

    Exam angle. An MCP server calls an internal API by forwarding the user's bearer token it received. It works, so what is wrong? The token was not issued for the MCP server, and the server cannot enforce its own scopes. Common trap: choosing "it keeps the user's identity" as a benefit.


    2.8 Races and pipeline integrity

    Check-then-act races. Two agents both read "1 seat left", both see it available, and both book it. Checking and then acting in two steps is the bug; wrapping them in a prompt instruction ("never double book") does nothing. Make the reservation atomic in the data store so exactly one succeeds.

    UPDATE seats
    SET held_by = :session_id
    WHERE seat_id = :seat_id AND held_by IS NULL;
    -- rows_affected = 1 means this caller won; 0 means it lost and must pick another

    Pipeline integrity. When answers cite the wrong page, the model is not necessarily at fault. A bad join between document ids and URLs, a stale index that was not rebuilt after a rename, or an ingestion job that shifted every id by one will all look like "the model invents links". Test the data path with a known-good sample: for ten documents, does id X resolve to the content and URL you expect? If the stored pairing is wrong, no prompt change will help. This is the same variable-isolation habit you will use in module 4.


    2.9 Stop reasons: retry or not?

    Not every response that ends early is a failure, and not every failure should be handled by trying again. A fallback path that treats "something went wrong" as one case will retry things that cannot succeed and fail over for problems a new provider will not fix. Classify first, then act.

    What you observe What it means Right handling
    429 or 529 Capacity or rate trouble; transient Backoff with jitter and retry-after; then queue, shed or fail over
    stop_reason: "max_tokens" The output cap you set was reached; the model did not finish Not an error and not transient. Raise the cap if it was too low, ask for a shorter format, or split the task. Repeating the same request with the same cap gives the same truncation
    stop_reason: "refusal" The model declined; a successful 200 response Application logic: tell the user, route to a human or a narrower path. Do not retry unchanged and do not count it as an outage
    A stop because the context window was reached The conversation plus the output no longer fit Reduce the input: compact, clear stale tool results, retrieve less. Waiting does not help
    stop_reason: "tool_use" or "pause_turn" The loop must continue Run the tool, or send the turn back to continue; neither is a failure

    The documentation lists the current stop_reason values and the exact name of the context-window stop; check it rather than hard-coding a list from memory.

    Figure 5. Route each early stop to its own handler

    flowchart TD accTitle: Stop-reason router accDescr: Every response or error is classified before any action. A normal end of turn is delivered. A 429 or 529 gets backoff with jitter and then queueing, shedding or failing over. A max_tokens stop means the output cap was reached, so the cap is raised, the format shortened or the task split. A refusal goes to the refusal policy and is not an outage. A context-window stop means the input must shrink. A tool_use or pause_turn stop means the loop continues. S["Response or error arrives"] C{"What ended it?"} A["Deliver the answer"] B["Backoff with jitter, then queue, shed or fail over"] D["Raise the cap, shorten the format or split the task"] E["Apply the refusal policy: tell the user or route to a human"] F["Shrink the input: compact, clear stale results, retrieve less"] G["Run the tool or continue the turn"] S --> C C -->|"end_turn, stop_sequence"| A C -->|"429 or 529"| B C -->|"max_tokens"| D C -->|"refusal"| E C -->|"context window reached"| F C -->|"tool_use, pause_turn"| G

    How to read this: one question at the top, six different owners below; only the 429 or 529 branch is about waiting, and none of the others is fixed by repeating the same request.

    TIP

    Picture it: An airport departures board. "Delayed" can mean weather (wait), an overweight bag (repack), a refused boarding pass (talk to a person) or a plane that is too small for the party (change the plane). Treating every delay as "wait and try again" sends the wrong people to the wrong desk. (Unlike a board, your handler must name the cause itself, from the stop reason.)

    A handler that branches on this table is short and testable:

    def next_action(resp):
        reason = resp.stop_reason
        if reason in ("end_turn", "stop_sequence"):
            return "deliver"
        if reason == "max_tokens":
            return "handle_truncation"      # raise cap, shorten, or continue deliberately
        if reason == "refusal":
            return "apply_refusal_policy"   # message, human route; never an outage signal
        if reason in ("tool_use", "pause_turn"):
            return "continue_loop"
        return "shrink_input_or_escalate"   # includes the context-window stop; check docs

    Truncated output is dangerous because it often looks valid. JSON cut at the cap fails to parse, or worse, a list silently stops after item 12. Detect it by checking the stop reason, never by "the text looks fine".

    NOTE

    Exam angle. When a scenario mixes several early-stop causes in one handler, ask of each: is it transient, a limit I set, a policy decision, or a size problem? Each has a different owner and a different fix. Common trap: one generic retry-then-fail-over rule for all four.


    2.10 Fallbacks across models, regions and platforms

    A fallback is a second route that serves the request when the first cannot. It can be a different model, a different region, or a different platform (the first-party API versus a Claude deployment offered through a cloud provider). Each kind of switch has its own risks.

    Fail over only for the right signals. Overload, timeouts and sustained 5xx justify a switch. A 400 will fail identically on the second route. A refusal is a decision about the content, and sending the same content to another route is a policy question for your team, not an availability tactic. A context-window stop needs a smaller input, or a route whose window actually fits it.

    Check feature parity before you switch. Features such as particular tools, caching behaviour, batch processing, beta capabilities, or the set of available model versions can differ between the first-party API and a cloud-platform deployment, and can differ over time. Request parameters and model identifiers are not guaranteed to be the same. Check the current documentation for the platform you use for what is available. Then decide per feature what the fallback does when the feature is missing: skip it, substitute a simpler path, or refuse to fail over for that request.

    Figure 6. A fallback chain that fails over only on the right signals

    Fallback chain with signal filter and parity checkRequest to Route policy; Route policy to Primary route (normal); Route policy to Parity check (overload, timeout); Parity check to Secondary route (features match); Route policy to Return error (never fail over)RequestRequestRoute policy: signal filterRoute policysignal filterPrimary route: pinned modelPrimary routepinned modelParity check: per featureParity checkper featureSecondary route: 1% canarySecondaryroute1% canaryReturn error: 400, auth, refusalReturn error400, auth,refusalnormaloverload, timeoutfeatures matchnever fail over

    How to read this: the solid path is normal service; the red dashed paths are the fallback and the blocked case. The secondary route is only used after the parity check, and the 1% canary keeps it exercised before the incident.

    TIP

    Picture it: The spare tyre in the boot. It is only useful if it is inflated, fits this car and you know where the jack is, and you find that out on a quiet Sunday, not on the hard shoulder at night. A fallback route you never drive on is a tyre nobody has checked.

    A fallback model is a different model. Output length, formatting, tool-calling habits and refusal behaviour all shift. Run the fallback route through the same evaluation as the primary, and consider whether degraded quality needs a visible marker (see 2.3).

    Test the path you never use. The fallback runs rarely, so it rots: expired credentials, an unconfigured region, a quota nobody requested, a changed parameter. Send a small steady stream of real or synthetic requests through it, and rehearse the switch.

    route_policy:
      primary:   { platform: first_party, model: "<pinned-id>" }
      secondary: { platform: cloud_platform, model: "<pinned-id>", needs_parity_check: true }
      fail_over_on: [overloaded, timeout, sustained_5xx]
      never_fail_over_on: [invalid_request, auth_error, refusal]
      canary_traffic_percent: 1   # keeps the secondary path exercised
    NOTE

    Exam angle. Look for the option that checks parity and exercises the secondary path, over the one that merely adds a second endpoint. Common trap: assuming the same request body works unchanged everywhere, and assuming a fallback that has never carried traffic will work during the incident.


    2.11 Queues, backpressure and tenant isolation

    When demand exceeds what the limits allow, something has to wait or be refused. Deciding what, in advance, is the design.

    Queue. Put non-interactive work behind a queue so that bursts become a steady rate. Size workers to your sustainable throughput, not to the number of jobs waiting.

    Backpressure. Tell producers to slow down instead of absorbing unlimited work. A bounded queue that rejects (or delays acceptance) once it is full is better than an unbounded queue whose wait time grows until everything times out.

    Load shedding. When even the queue is too long, drop the least valuable work first: low-priority, optional or easily recomputed requests. Shedding gives a fast, explicit "try later" to some users, instead of a slow failure for all. Keep a reserve for interactive traffic so a bulk import cannot take all capacity.

    Multi-tenant fairness. One organization-level limit is shared by every tenant of your product, so one heavy tenant can use the capacity another one needs (a noisy neighbour). A second API key does not help, because the limit is organizational. Isolation is yours to build:

    • Per-tenant admission limits (a token bucket per tenant for requests and for estimated tokens).
    • Fair scheduling between tenants rather than one first-in-first-out line.
    • Separate lanes: interactive traffic gets a reserved share; bulk work goes to a lower-priority lane or the Batch API.
    • Workspace-level limits to partition capacity between products, where your account supports them.

    Figure 7. Admission, lanes and fair scheduling

    Per-tenant admission, separate lanes and fair schedulingTenant A to Admission (requests); Tenant B to Admission (requests); Admission to Interactive lane (admitted); Admission to Bulk lane (admitted); Interactive lane to Workers; Bulk lane to Workers; Admission to Rejected (bucket empty)Tenant A: interactiveTenant AinteractiveTenant B: bulk importTenant Bbulk importAdmission: bucket per tenantAdmissionbucket per tenantInteractive lane: reserved shareInteractivelanereserved shareBulk lane: lower priorityBulk lanelower priorityWorkers: fair schedulerWorkersfair schedulerRejected: try again laterRejectedtry again laterrequestsrequestsadmittedadmittedbucket empty

    How to read this: each tenant spends from its own bucket at the gate, so a bulk import runs out of tokens before it can crowd out the interactive lane; the red path is the explicit "try later" instead of a slow failure.

    TIP

    Picture it: A restaurant kitchen with a ticket rail that holds a fixed number of orders. When the rail is full, the host tells new tables to wait; the kitchen does not pile tickets until the rail collapses. Takeaway orders use a separate shelf, so a catering order for sixty cannot block the diners at table four.

    def admit(tenant, est_tokens):
        bucket = buckets[tenant]                  # one bucket per tenant
        if not bucket.try_take(est_tokens):
            return reject(retry_after=bucket.seconds_until(est_tokens))
        return queue_for(tenant).put_nowait(...)  # fair scheduler drains per-tenant queues
    NOTE

    Common trap: answering a noisy-neighbour symptom with more retries or a larger shared queue. Both make the heavy tenant's backlog everyone's latency. The fix is per-tenant limits and lanes.

    NOTE

    On call, 3 a.m.: Tomas Reyes runs the platform team at Quillwork, a document-tools company. Just after midnight one customer starts a bulk import of old files, and by 00:40 the support chat of every other customer takes over a minute to answer. All tenants share one queue and one organization limit, so the import fills the line and everyone waits behind it. Tomas adds a bucket per tenant, a reserved interactive lane and a bulk lane that the import is moved to. The next import runs slowly and nobody else notices. Invented example.


    2.12 Capacity planning: find the binding constraint

    Three kinds of limit can cap you, and only one of them is binding at a time: requests per minute, input tokens per minute, and output tokens per minute. Capacity planning means computing the ceiling each one implies for your actual traffic shape and finding the lowest.

    Worked example (invented limits). Assume a limit of 1,000 requests, 1,500,000 input tokens and 300,000 output tokens per minute. Each request has 5,000 input tokens and 400 output tokens.

    Constraint Ceiling Working
    Requests 1,000 per minute the limit itself
    Input tokens 300 per minute 1,500,000 / 5,000
    Output tokens 750 per minute 300,000 / 400

    Input tokens bind at 300 requests per minute. Asking for more requests per minute would change nothing. Levers that target the binding constraint: trim the prompt, retrieve less, or cache the stable part. Tokens read from the cache do not count toward the input-per-minute limit (see 2.2). If 4,500 of the 5,000 tokens are a cacheable stable prefix, about 500 uncached tokens count, the input ceiling rises to 1,500,000 / 500 = 3,000, and the binding constraint moves to output tokens at 750 per minute. Now the useful lever is shorter outputs, or moving non-urgent work elsewhere.

    Batch economics is a third kind of constraint. A backlog that is not time-critical does not have to use real-time capacity at all. Batch processing is billed at a discount and is asynchronous (module 5), so the question becomes whether the deadline allows waiting. A bulk job with a 24-hour deadline is a batch job even if it would fit the real-time limit.

    Plan with headroom, because the bucket refills continuously and bursts can still trigger 429s; a ramp limit can also reject a sudden jump. Re-run the arithmetic whenever the prompt, the output length or the model changes, since each moves the binding constraint.

    NOTE

    Exam angle. Compute the ceiling for each limit before choosing the lever. Common trap: asking for a higher requests-per-minute limit when the token limit is the one being hit.


    2.13 Remote MCP, versioning and gateways

    Section 2.7 covered validation, paths and token handling. Running an MCP server remotely, for many clients over time, adds three more concerns.

    Deployment and authentication. A remote server is an ordinary networked service: terminate TLS, authenticate every call with tokens issued for that server, rate-limit per client, and log security-relevant actions. Prefer stateless handlers where the protocol allows, so you can scale instances and roll them without losing sessions. Configuration (transports, how a client is told which server to trust) differs between hosts and platforms; check the current documentation for the client or platform you use rather than assuming parity.

    Tool and schema versioning. The tool name, its description and its input schema are an interface that models read like a prompt. Treat changes with care:

    Change Risk
    Add an optional parameter Usually safe
    Rename a tool or parameter, change a type, or change what a field means Breaking: callers and cached examples fail or silently behave differently
    Reword a description Not an API break, but it changes which tool the model picks; evaluate it
    Change the output shape Breaks anything that parses it, including the model's expectations

    Introduce a breaking change as a new tool or version alongside the old one, deprecate on a schedule you announce, then remove. Contract tests (a fixed set of requests with expected outputs) plus an agent-level evaluation catch both interface breaks and behaviour changes.

    Gateways. A gateway in front of MCP servers or model calls centralises authentication, per-team limits, routing, audit logging and an allowlist of approved servers. It does not remove the earlier rules: the gateway must still not forward a client's token to an upstream it was not issued for, and a broad shared credential at the gateway is a larger blast radius, not a smaller one.

    NOTE

    Exam angle. If a tool needs a breaking change, the best answer ships it side by side with the old version and tests both. Common trap: renaming a parameter in place because "the model will adapt".


    2.14 Prompt versions, model migration and rollout

    Prompts, tool definitions and model identifiers change behaviour as surely as code does, so they need the same release discipline.

    Version everything that shapes behaviour. Store the prompt, tool schemas, model ID and parameters together as one versioned release, and log the version on every request so you can tie a regression to a release. Pin the model identifier explicitly rather than following an alias that can move.

    Migrating to a new model version is a behaviour change, not a config edit. Verbosity, formatting, tool-calling habits, refusal rates and output length can all shift. "Does it still return valid JSON" is not enough. Run the golden set and the behavioural checks against the new version, compare per segment, and read the failures.

    Change one thing at a time. If you swap the model and rewrite the prompt in one release and quality drops, you cannot tell which did it. Release the model change first with the old prompt, then the prompt change.

    Roll out progressively with a way back.

    1. Offline evaluation against the release criteria.
    2. Shadow mode: run the candidate on live traffic, log its outputs, serve the old ones.
    3. Canary: send a small share (for example 1 to 5 percent) of real traffic to the candidate, with automatic comparison on quality, refusal rate, latency, cost and error rate.
    4. Expand in steps while the metrics hold.
    5. Roll back by switching one config value to the previous release, with no rebuild.

    Define the rollback triggers before the rollout starts, such as "refusal rate up by more than a set margin" or "grounding check failures up", so the decision is not made under pressure.

    Mind the side effects. A new system prompt invalidates the prompt cache for that prefix (module 5), so the first minutes of a rollout cost more and run slower. A prompt that works in a 1% canary can still hit a rate limit at 100%, so recheck capacity (2.12).

    NOTE

    On call, 3 a.m.: The Harbourline support team moves to a newer model version and sends it to 5 percent of conversations first. Within the hour the dashboard shows the refusal rate on the new version running clearly above the old one, which was one of the rollback triggers written down before the release. Maya Okafor flips one config value to the previous release and the 5 percent returns to the old model in under a minute. Nobody outside that slice saw a difference, and the team now has a labelled set of the refusals to study. Invented example.

    NOTE

    Exam angle. Prefer the option with offline evaluation, a canary and an instant rollback path. Common trap: "swap the model ID for everyone and watch the complaints".


    2.15 Agentic search, RAG and hybrid retrieval

    There are two broad ways to give a model knowledge it was not trained on.

    Classic RAG runs a fixed retrieval step before generation: embed the query, fetch top chunks, put them in the prompt. It is cheap, fast and predictable, and works well when questions map to one or two passages in a well-indexed corpus.

    Agentic search gives the model search tools (a search API, file listing, grep, a database query) and lets it decide what to look for, read results, refine and search again. It handles multi-hop questions, vague queries and corpora where a single embedding query is a poor fit. The costs are more model calls, higher and more variable latency and token use, and a need to cap steps and budget.

    Situation Leans toward
    High volume, simple factual lookups, tight latency Classic RAG
    Question needs several lookups, each depending on the last Agentic search
    Exact identifiers, codes, error strings Keyword (lexical) search
    Paraphrased natural-language questions Embedding (semantic) search
    Mixed query styles Hybrid

    Hybrid search combines lexical matching (such as BM25) and embedding similarity, then merges their rankings, for example with reciprocal rank fusion, and often reranks the merged list (2.5). Embeddings alone tend to miss exact tokens such as part numbers; keywords alone miss paraphrases. Hybrid is the usual answer to "it finds general questions but fails on product codes".

    Chunking and embedding choices interact. Chunks must be small enough to be specific and large enough to carry their meaning (2.4). The embedding model decides what "similar" means: a model trained on general text may handle domain vocabulary poorly, and changing it means re-embedding the whole corpus, so version the index. Query and document must be embedded with the same model. Evaluate on your own labelled questions rather than on a general benchmark.

    Agentic search does not remove the earlier rules. Filters and tenant isolation still sit in the tools, not the prompt; the search tool must enforce them whatever the model asks for. Cap the number of steps.

    NOTE

    Exam angle. Choose by the question shape and the latency and cost budget, and treat hybrid as the answer for exact-token failures. Common trap: replacing retrieval with a bigger context window or a more autonomous agent when the real issue is a missing keyword path.


    2.16 Diagnose retrieval by stage and declare uncertainty

    "The answers are wrong" is not a diagnosis. A retrieval pipeline has stages, and each can fail in a way that looks the same from the outside. Measure at each stage with labelled questions, where each has a known answering passage.

    Stage Question to measure A failure looks like
    Ingestion and parsing Does the answering text exist in the index, readable? Scanned or oddly formatted files yield empty or garbled text
    Chunking Is the passage intact and interpretable? Table values without headers
    Embedding and index Is it retrievable by plausible queries? Domain terms and codes never match
    Query formation Does the query express the need? Multi-part question retrieves one topic
    First-stage recall Is it in the top k candidates? Present in the index, absent from candidates
    Ranking Is it near the top? In the top 30, not in the top 3
    Context assembly Did it reach the prompt, within limits? Truncated or crowded out by duplicates
    Generation Given the right context, is the answer faithful? Contradicts or ignores the passage
    Verification Are claims checked against sources? Fabricated citations pass

    Count the failures per stage, start at the earliest stage with a large share, and re-measure. Early failures cap everything later: if the text never reached the index, no reranker or prompt can recover it.

    Confidence signals and declaring uncertainty. A grounded system should say when it does not know. Useful signals, in rough order of reliability: whether any chunk passed a relevance threshold you calibrated on labelled data; whether citation verification (2.6) passed; whether independent retrievals agree; and the model's own stated confidence, which is the weakest because it can be confidently wrong. Calibrate thresholds against labelled cases, and measure both wrongly answered and wrongly refused questions.

    When signals are weak, return a plain "I could not find this in the documents" with what was searched, or escalate. A clean "not found" is better than a confident invention.

    NOTE

    Exam angle. Pick the answer that attributes failures to stages before changing a component. Common trap: adding a reranker or a larger model before checking that the answer is in the index.

    IMPORTANT

    Remember this:

    • Retry only transient failures, with a cap, backoff, jitter and retry-after; let one layer own the policy.
    • A refusal is a normal answer, not an outage: it never counts toward the breaker.
    • Rules that must always hold live in code or in the lock, not in the prompt.
    • Name the cause of an early stop first; each one has a different owner and fix.
    • Find the binding constraint before asking for more capacity, and test the fallback before the incident.

    M2 Checkpoint

    You should be able to:

    • Classify an API error as transient or non-transient, and design a retry policy with backoff, jitter, a cap and retry-after.
    • Explain why rate limits are organizational and why extra API keys do not add capacity, and name two levers that do.
    • Say what a circuit breaker should and should not count, and why a refusal is application logic.
    • Describe a degraded mode with a visible indicator and an action that starts before the breaker threshold.
    • Choose between structure-aware chunking, pre-filtering, reranking and multi-facet retrieval from a symptom.
    • Decide when isolation needs physical separation instead of a metadata filter.
    • Verify generated claims and citations against retrieved sources in code.
    • Name three MCP production controls: input validation, path canonicalisation, audience-checked scoped tokens without passthrough.
    • Fix a check-then-act race with an atomic operation.
    • Classify an early stop (rate limit, max_tokens, refusal, context-window stop, tool or pause turns) and handle each differently.
    • Design a cross-model, region or platform fallback that fails over only on the right signals, checks feature parity and is exercised before the incident.
    • Use queues, backpressure, load shedding and per-tenant limits and lanes to keep a noisy tenant from starving the others.
    • Compute the ceiling each limit implies and name the binding constraint (requests, input tokens, output tokens or batch economics) before choosing a lever.
    • Version MCP tools and schemas, ship breaking changes side by side, and say what a gateway adds and what it does not remove.
    • Version prompts and model IDs together, test a model migration on the evaluation, and roll out through shadow, canary and an instant rollback.
    • Choose between classic RAG, agentic search and hybrid retrieval from the question shape, latency and cost.
    • Diagnose a retrieval failure by stage, and use calibrated confidence signals to declare uncertainty instead of inventing an answer.

    Where to verify

    Anthropic and protocol documentation read while writing this module:

    Chunking, filtering, reranking and atomic reservation are general engineering practice rather than Anthropic-specific claims; test them against your own data.

    Enroll to keep reading

    Lesson 3 of 10 · Claude Certified Developer — Professional

    Retry rules, rate limits, circuit breakers, refusals, RAG design, claim verification and MCP security for Claude apps that must stay up in production.

    In the rest of this lesson

    • 2.7 MCP in production
    • 2.8 Races and pipeline integrity
    • 2.9 Stop reasons: retry or not?
    • 2.10 Fallbacks across models, regions and platforms
    • 2.11 Queues, backpressure and tenant isolation
    • 2.12 Capacity planning: find the binding constraint

    Enrolling is free. It unlocks every lesson in Claude Certified Developer — Professional, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Free: CCA Foundations cheat-sheet (PDF)

    The domains, the 3 universal rules, core concepts, and exam-day shortcuts — one page. Enter your email and it's yours, plus my weekly AI-architecture notes.

    No spam. Unsubscribe any time.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments