Case brief
Understand the scenario, task, and constraints.
Four constraints on every support turn
Design a gateway for a customer-support agent that survives a provider outage without customer-visible downtime, resists prompt injection and personally identifiable information (PII) leaks, spends less than $500 per day, and keeps p95 latency below three seconds. P95 means 95% of the measured requests finish within that time. The first discovery question is what counts as finishing: the first streamed token or the complete answer.
A gateway is the shared path through which model traffic passes. It screens, meters, routes and recovers each call. A customer message may trigger an agent turn with several model and tool steps. Screening only that message leaves the later paid calls outside the budget and recovery controls.
This case is for engineers preparing for Forward Deployed, solutions and applied AI interviews. It assumes familiarity with model APIs, token pricing, API gateways, retries and circuit breakers. Work through the dollar arithmetic before reading the solution, then rehearse the design and cost pivot. The target is an explainable design, not a deployed gateway. The source is a mock design built from a production and operations tutorial: its prompt, seven-point rubric and strong-answer outline supply the constraints. Pricing, latency and residency receive further worked treatment here.
All model names, prices, durations and traffic assumptions below belong to the captured case. They are historical whiteboard inputs, not current vendor offers or measured service guarantees. The captured reference reports its price check as 27 September 2026. No current price verification is claimed.
Trace a support request
Consider an illustrative customer asking a support question that includes an account number. Authentication identifies the session and policy assigns its data class. The input guard masks PII before cache lookup or any provider call. A safe FAQ cache hit can answer immediately after output validation. Live account answers bypass reusable caching.
On a miss, the gateway counts tokens, checks budget admission, classifies complexity and checks intent. A simple turn takes a small-model route. An agent turn may make five calls, each admitted and metered through the model face. A failed provider moves the request to an allowed fallback only while time and budget remain. The customer receives a validated answer with its model source, a labelled degraded response, or a human handoff. An agent instead receives a typed failure when no trustworthy model response is available.
Next: build the answer in interview order.
Start the walkthroughDesign walkthrough
Follow the reasoning from discovery to delivery.
1. Place the gateway on both sides of the agent
The edge face screens customer input and final agent output. The model face sits between every agent or evaluator call and its provider. The source playbook estimates that one user request can become 5 to 20 sub-requests. Budget enforcement at the edge alone therefore misses most of an agent's spend and leaves later failures unrecovered.
One source-reported research platform uses a shared sidecar: agents ask for a function, and configuration maps that function to a provider. When a provider changes, the team changes one mapping rather than provider code in five places. This is the shared function-to-model layer a platform can extend to further agents.
Ask the five questions in the table before drawing. The case assumes 10,000 daily users and three turns each, one customer across several regions, and a prohibition on PII reaching an unauthorised customer or provider. Residency remains an explicit discovery question. Use first token for multi-step turns and full answer for one-call turns only after agreeing that interpretation with the interviewer.
The action-authorisation gateway described in the source's Customer Support Automation reference has another job: deciding which actions an agent may take. A real support product may need both. The model traffic gateway described here does not grant refund or booking authority.
| Question | Why it matters | Assumption for this page |
|---|---|---|
| How many conversations a day, and how many turns each? | Sets the spend the $500 must cover | 10,000 users a day, borrowed from the playbook's support-chatbot case; 3 turns each |
| Is 3 s the time to first token or to the full answer? | An agent turn with several tool steps usually cannot finish in 3 s | First streamed token for agent turns; full answer for one-call turns |
| One tenant or many? | Decides whether budgets, caches and residency are per tenant | One customer, several regions |
| Can data leave the customer's network or region? | The source's named gap; changes which providers are legal | Unknown; see the residency topic for both cases |
| What must never happen? | Sets which checks fail closed | PII leaks to a customer or a provider it should not reach |
2. Make each constraint fail a test
Turn each requirement into a test and assign an owning component. During a single-provider outage, every customer response must be answered, labelled as degraded, or handed off. That is a useful availability test. It does not establish that all outages can produce an equivalent model answer.
The latency targets are p95 under three seconds to first token on every turn and to full answer on one-call turns. Enforce the daily $500 ledger before admission. The illustrative per-call input cap is 8,000 tokens. Reject an oversized call explicitly rather than silently truncating context.
Version the red-team suite and block release when a known attack passes through input or output checks. This is a finite regression requirement. It cannot establish zero residual injection risk. Apply PII policy to responses and logs, tag every answer with model and provider, and retain enough trace information to reconstruct guard decisions, route, tokens and cost.
Safe caching, region routing, real-path red teaming and versioned configuration make these requirements operable. The tables connect each requirement to a component, so an interview answer can name who enforces it.
| Constraint | Stated so it can be tested |
|---|---|
| Availability | A single-provider outage produces zero customer-visible errors; every response is answered, degraded with a label, or handed to a human |
| Latency | p95 under 3 s to first token on every turn; p95 under 3 s to full answer on one-call turns |
| Daily spend | Under $500/day, enforced by a live ledger, never discovered on the invoice |
| Per-request spend | Rejected before the paid call if it exceeds a token cap (assumption: 8,000 input tokens per call) |
| Injection | Every attack in the red-team suite blocked at input or at output; no release if one passes |
| PII | No PII from one turn appears in a response or a log unless policy allows it |
| Attribution | Every response tagged with the model and provider that produced it |
| Replay | Any request reconstructable from its trace: guardrail decisions, route, model, tokens, cost |
| Requirement | Primary component(s) |
|---|---|
| Screen input | Rule-based input guard, then LLM input guard |
| Screen output | Rule-based output validator, then optional LLM output check |
| Cheapest capable model | Complexity router |
| Survive outage | Provider adapters with retry and breaker, fallback provider, degradation responder |
| Stay under budget | Token-budget check, spend ledger and pacer |
| Replay | Tracer, structured logs, metrics collector |
| Residency | Data-class policy and region-bound provider pool |
3. Calculate the $500 day
Use 30,000 turns a day: 10,000 users multiplied by three turns. A 30% cache hit rate removes 9,000 generation paths. Of 21,000 misses, 70% are simple one-call turns and 30% are complex five-call turns. Five calls is the low end of the source's 5 to 20 sub-request rule. Each call has 2,000 input and 250 output tokens. A flat 2,000 per call assumes each agent step sends a bounded context. If every step re-sends the conversation plus earlier tool results, input tokens climb step by step, so measure the per-step growth before trusting the complex-turn price.
At the historical illustrative small-model rates of $0.15 input and $0.60 output per million tokens, one call costs (2,000 × 0.15 + 250 × 0.60) / 1,000,000 = $0.00045. At the large-model rates of $2.50 and $10.00, the call costs $0.0075. Five such calls cost $0.0375.
Multiply those unit costs by 14,700 simple turns and 6,300 complex turns. Add $1.05 for 21,000 router classifications at $0.00005 and $1.35 for 15,000 input checks at $0.00005 plus 6,000 output checks at $0.0001. The total is $245.265, reported as about $245 or 49% of budget. Simple turns come to $6.615, shown as $6.62 in the table. Cache hits cost no generation tokens in this model, but still require gateway infrastructure and safety processing.
Without caching or routing, 30,000 five-call large-model turns cost $1,125, or 2.25 times the cap. Complex turns are 21% of all traffic and about 96% of this modelled spend. Increasing their share of misses from 30% to 40% raises daily spend to about $323. Holding all rates and proportions constant, $500 buys roughly 61,000 turns. That is a sensitivity estimate, not a capacity promise.
| Assumption | Value |
|---|---|
| Customer turns per day | 10,000 users × 3 turns = 30,000 |
| Cache hit rate | 30% of turns, so 9,000 turns avoid generation cost |
| Router split of the 21,000 misses | 70% simple, 30% complex |
| Simple turn | One call to the small model |
| Complex turn | An agent path of 5 calls to the large model, the low end of the playbook's 5 to 20 rule of thumb |
| Tokens per call | 2,000 in, 250 out |
| Small model price | $0.15 in, $0.60 out, per million tokens (illustrative: the captured source's September 2026 GPT-4o mini pricing example, not a current offer) |
| Large model price | $2.50 in, $10.00 out, per million tokens (illustrative: the captured source's September 2026 GPT-4o pricing example, not a current offer) |
| Router classification | About $0.00005 per call on the small model |
| LLM input guard | Fires on half of turns, about $0.00005 each |
| LLM output check | Fires on 6,000 turns, about $0.0001 each |
| Line | Arithmetic | Per day |
|---|---|---|
| Cache hits | 9,000 × $0 | $0 |
| Router | 21,000 × $0.00005 | $1.05 |
| Simple turns | 14,700 × $0.00045 | $6.62 |
| Complex turns | 6,300 × $0.0375 | $236.25 |
| Guards | 15,000 × $0.00005 + 6,000 × $0.0001 | $1.35 |
| Total | about $245, 49% of the budget |
4. Trace components and failure ownership
The source diagrams show the same request path in several arrangements, with a versioned control plane above it. Read them as one system rather than competing designs. The control plane holds guard rules, banned phrases, routes and thresholds, prompts, provider and residency registry, budgets, pacing and red-team versions. Bad configuration must roll back atomically rather than leave half the workers on unsafe policy.
Authentication and rate limits reject unauthorised traffic before it can spend money. The microsecond rule guard blocks injection patterns and masks PII. Cache lookup follows masking. A cache failure becomes a miss. The token check rejects oversized calls. The complexity router chooses a capable model, defaulting to a safe route on failure. The LLM intent guard may be skipped only for policy-approved low-risk, previously seen patterns.
Every agent call reaches the spend ledger and pacer. Adapters wrap providers in deadline-bounded retry and a breaker. If A fails, B receives a portable prompt and tool schema. If both fail, the edge responder labels degradation or hands off. Output rules always validate PII and banned content, with a semantic check for risky replies. A cache write occurs only after output validation passes.
The ordering phrase screen, meter, route, recover describes responsibilities rather than permission to make an unmetered router or guard call. All paid classifier, guard, retry and fallback calls need admission too. The control-plane table and figures preserve the original component responsibilities and failure modes. Telemetry writes asynchronously with request traces, metrics, JSON events, cost tags and model tags.
| # | Component | Responsibility | Fails how |
|---|---|---|---|
| 01 | Auth and rate limit | Identifies the user and session, tags the data class, applies per-user limits | Closed: unauthenticated traffic never reaches a model |
| 02 | Rule-based input guard | Injection regex and PII detection and masking, in microseconds | Closed: a match blocks with a logged reason |
| 03 | Cache | Exact match first, semantic only if traffic shows paraphrase-heavy repeats | Degrades: a cache outage is a miss, never an error |
| 04 | Token budget | Rejects an oversized request before the paid call | Closed: explicit rejection, never silent truncation |
| 05 | Complexity router | Small model labels the turn simple or complex | Degrades: on router failure, default to the safe route |
| 06 | LLM input guard | Small model classifies intent, catching rephrased attacks | Degrades by policy: skip only for low-risk, previously seen patterns |
| 07 | Spend ledger and pacer | Charges every call's real tokens to the day; tightens routing as spend climbs | Closed at 100%: no new paid calls; cache and handoff only |
| 08 | Provider adapter A | Retry with backoff inside a per-provider breaker | Degrades: breaker trip sends traffic to B at once |
| 09 | Provider adapter B | Same pattern, portable prompts and tool schemas | Degrades: both down reaches the degradation responder |
| 10 | Degradation responder | Labelled answer from cached context, or a human handoff | Returns the labelled fallback outcome; if the gateway itself is unavailable, the channel must offer a separate human-contact path |
| 11 | Rule-based output validator | Re-runs PII detection, checks banned phrases | Closed: block with a logged reason |
| 12 | LLM output check | Semantic policy check on risky replies | Degrades: off for low-risk replies to save latency |
| 13 | Telemetry | JSON logs, metrics, one trace per request, cost and model tags | Degrades: async, sampled; never on the hot path |
| 14 | Control plane | Rules, routes, prompts, providers, budgets as versioned config | Closed: a bad config rolls back, never half-applies |
5. Validate before shipping configuration
Exercise the actual authenticated endpoint, rate limits and guard path with the versioned red-team suite. Test a primary outage, fallback quota exhaustion, both providers unavailable, cache outage and each budget threshold. Verify that a region-bound request never escapes its pool, including during recovery. Confirm a model-face typed failure cannot be mistaken for a successful tool response.
Use labelled traffic to compare routing cost with misrouting and resolution rate. Measure first-token and full-answer latency separately by route. Test PII redaction in cache, responses, logs and traces. Replaying a bad run must identify the prompt version, guard reason, selected model, retries and final outcome.
Ship prompts, policy and routes as versioned configuration with rollback. Keep the fallback warm with the source's illustrative 1% live traffic share and verify it can accept full-load quota before an outage. The walkthrough's validation and rollout sequence is an authored synthesis of the source's tests and control-plane requirements.
Technical deep dives
Examine mechanisms, alternatives, and operational consequences.
Rules, intent checks and streaming boundaries
Rules check regex patterns, length, schemas and banned phrases in microseconds without a per-model-call bill. They cannot recognise every paraphrase: “pretend the rules above never existed” may evade literal injection patterns. A small-model guard classifies the intent of the surviving text and can recognise that rephrase, while spending money and a few hundred milliseconds.
Run checks in both directions. Mask a customer's PII before forwarding input. Validate output because a model can repeat something the customer supplied two turns earlier. A clean current input cannot prove that conversation history is safe to disclose.
Moderation applies a fixed general harm taxonomy, including harassment, hate, self-harm, sexual content and violence. Category scores determine flags. The source reports that mild rudeness such as “you are very poor ha ha” passed its moderation test. Product guardrails separately enforce support scope and system-prompt secrecy. A moderation pass does not mean a product-policy pass.
Log a reason for every block, return a safe reply and retain evidence for security review. A source-reported research platform attacks its own public endpoint through the normal auth, rate-limit and guard path. Include custom vulnerabilities for narrow policy exceptions: an apparently reasonable exception can reveal exactly the fact an attacker asks for. Both rule and LLM defences remain probabilistic. Report measured residual risk rather than invent a zero-risk promise.
Exact and semantic caching have different mechanisms
An exact cache normalises the PII-masked query and hashes it into a lookup key. “What is Python?” and “Tell me about Python” remain different inputs. A class called SemanticCache that only hashes text still implements exact matching.
A semantic cache embeds the query into a vector and searches nearby stored vectors. A tuned similarity threshold decides whether a paraphrase can reuse an answer. A loose threshold can return mismatched or stale answers. Start with exact matching and introduce vector lookup only when observed traffic contains enough repeated paraphrases to justify its risk and operating cost.
Include tenant, user permission, document version and prompt version in the response key. Cache reusable FAQ responses, never live account answers. Masking makes this rule necessary rather than optional: "What is the balance on [ACCOUNT]?" from two customers masks to the same text and the same key, so cacheability must come from the request's data class and intent, decided before lookup, not from the key alone. Changing a prompt or knowledge version deliberately invalidates prior entries. Invalidate on document, access-control list (ACL) or metadata changes. Freshness and permission checks still apply to semantic hits.
A sudden hit-rate drop is a reason to inspect keying, versioning, traffic mix and invalidation before adding capacity. Output validation precedes writes: a blocked answer must never become a future cache hit.
Classification, token admission and daily pacing
The router requests a structured simple-or-complex label from a small model. A schema constrains the label rather than accepting arbitrary prose. Choose a threshold on labelled real traffic. Sending a simple request to the large model wastes money. Sending a complex request to a weak route can reduce resolution. Compare the cost saving with the product's tolerated misrouting rate.
A token cap catches one oversized request or runaway context. A daily ledger catches many ordinary calls adding up. Use a real tokenizer for the pre-call count, then reconcile with provider-reported usage. The rough examples len(text.split()) × 1.3 and len(text.split()) × 4 // 3 are trend approximations, not reliable admission accounting.
The pacer responds before exhaustion. At 80% spent, tighten routing toward cheaper paths. At 95%, allow the small model and hand complex work to humans. At 100%, allow cache and handoff only. In this case, “raise the router threshold” means require stronger evidence before taking the expensive route. A plain hard cap that runs out at 4 p.m. cannot meet the customer availability goal.
Implementation caveat added for the teaching design: concurrent calls need atomic budget reservations for their bounded potential cost, followed by usage reconciliation. Otherwise several individually admitted calls can overspend the same remaining balance. Output-token caps, retry reservations and classification/guard spend belong in that reservation. The source describes pre-call caps and a live ledger but does not supply this concurrency protocol.
| Control | Catches | Action |
|---|---|---|
| Per-request token cap | One oversized prompt or runaway context | Reject explicitly before the call, never truncate silently |
| Daily ledger and pacer | Many ordinary requests adding up | At 80% spent, raise the router threshold; at 95%, small model only plus human handoff for complex turns; at 100%, cache and handoff only |
Retry, breaker, fallback and degradation
A retry handles a transient connection drop or provider rate limit. Exponential backoff with jitter spreads clients across time. Fixed intervals synchronise retries into a thundering herd. When a provider's 429 carries a Retry-After header, treat that wait as the floor for the next attempt, and fail over at once if it exceeds the request's remaining deadline. The source's general pattern allows three to four attempts, but interactive requests must obey a deadline instead.
The breaker wraps the retried provider call and remembers dependency health. The illustrative settings are failure_threshold=3 and cooldown_seconds=5.0. Closed admits calls. Open rejects immediately. After cooldown, half-open admits a probe. Success permits recovery. Without the probe, the breaker has no path back to healthy. Under flapping load, count failures over a sliding window and require more than one successful probe before closing.
Fallback sends work to an independent provider when retries run out or the breaker opens. Attribute every response to its actual provider and model to measure cost and quality drift. Portable prompts and tool schemas prevent a different tool-calling format from silently breaking the agent. Keep the backup warm, verify quota at full load, and distinguish provider 429 responses from your own gateway limits.
When neither provider can answer, the edge can return a labelled response seeded from safe cached context, or log a ticket for a person. The model face must return a typed error. Giving an agent a degraded prose string as if it were a real model answer can cause a refund or booking against stale information. Recovery also obeys residency and spend policy.
Three collisions inside the three-second target
The source estimates roughly 1 ms for the rule guard, 5 to 10 ms for cache, 200 to 400 ms for the router, 1 to 2 seconds for the main model and 1 ms for output rules. At the upper ends, 1 + 10 + 400 + 2,000 + 1 = 2,412 ms, or about 2.4 seconds. These are whiteboard durations rather than measured percentiles. Summing stage estimates does not establish an end-to-end p95.
A risky-output LLM check adds 300 to 500 ms, reaching about 2.9 seconds. An additional serial input guard at an assumed 300 to 500 ms reaches about 3.4 seconds and breaks the target. Router and input guard read the same masked input, so they can run in parallel: their contribution becomes the slower duration. Skip the LLM input check only for policy-approved low-risk, previously seen patterns.
Five sequential model calls at 1 to 2 seconds take 5 to 10 seconds. Because complex turns are 21% of traffic, p95 full-answer latency lands inside the slow population. Agree first-token measurement for agent turns. Parallelise independent read-only tool work, and send common intents through a one-call workflow or router where an agent adds no value.
Backoff of 0.3, 0.6 and 1.2 seconds spends 2.1 seconds before attempt four even starts. Attempt timeouts make it worse. Give each interactive request a deadline, permit one retry only when enough time remains, then fail over. Once open, the breaker skips A immediately. The earliest affected callers still pay detection and timeout cost, bounded by the trip policy.
Streaming creates another boundary: a validator cannot retract words already displayed. The same applies to recovery. If the primary fails after tokens have reached the customer, the fallback cannot silently continue the sentence from a different model. Discard the partial answer with a visible restart notice, or hand off, and record both providers on the trace. Run rule checks sentence by sentence before release. Buffer risky replies, including refunds or account data, until the LLM output check finishes. Reconcile that buffering with the first-token target rather than claiming both unconditional streaming and complete pre-display semantic review.
| Path | Sum | Verdict |
|---|---|---|
| Common path | ~1ms + ~10ms + ~400ms + ~2s + ~1ms | About 2.4 s: fits |
| Plus LLM output check | + 300-500ms | About 2.9 s: tight |
| Plus LLM input guard in series (assumption: 300-500ms) | + 300-500ms | About 3.4 s: breaks |
Trace enough state without copying PII
Structured logs explain one request, metrics count outcomes across traffic, and traces identify the stage that caused a silent wrong answer. A successful HTTP status is insufficient evidence of a correct support response.
Retain these source trace fields: tenant_id, feature, prompt_version, model, input_tokens, output_tokens, estimated_cost, latency breakdown, retrieval top-k, reranker used, cache status, tool calls, retries, timeout status and final outcome. Add the provider, guardrail decision and block reason. Retrieval fields apply when a request actually uses retrieval, rather than implying every gateway call does.
Redact before writing. Copying raw prompts into logs duplicates PII outside the answer validator. Sample successes, keep every failure with safe redacted detail, assign retention and write asynchronously. Synchronous logging can cause a post-deploy latency jump. Restricted requests require equally restricted traces, including their storage backend.
The dashboard has six signals: daily spend against the pacing line, p95 first-token latency, fallback rate by provider, breaker state, guard block rate by rule and cache hit rate. Spend changes start with route and prompt version. Hit-rate changes start with key/version/traffic/invalidation. Fallback changes start with provider health, quota and breaker decisions. The source points to Observability and Production Diagnosis for replay and cost-spike investigation. Those linked chapters were not captured here.
Constrain the provider pool before failover
The underlying tutorial explicitly leaves residency unresolved when no third-party provider can receive the customer's data. The captured gateway case develops its suggested in-VPC or self-hosted model path. A virtual private cloud (VPC) is the customer's isolated cloud network.
At the edge, policy and PII findings assign a data class. Each class maps to an allowed pool before routing. Public content can use approved providers. Maskable PII must be masked before leaving the network. Region-bound data requires an in-region endpoint with contractual no-retention or a model in the customer's VPC. Data forbidden to leave the network stays on a self-hosted model there.
Give each restricted pool its own recovery path: another in-region endpoint, another self-hosted replica set, or human handoff. Falling back to a global pool violates residency even if it restores an answer. Logs and traces follow the same boundary. The source notes that its worked tracing examples are hosted, leaving a self-hostable backend as implementation work.
Self-hosting changes token spend into GPU-hour capacity. The source sizing formula is Replicas = ceil((QPS × Tokens_request) / (TokensPerSecond_replica × UtilizationTarget)). Queries per second multiplied by tokens per request gives token throughput demand. Divide by sustainable throughput per replica at the target utilisation, then round up. If the resulting count exceeds available hardware, reduce or reshape workload rather than assume more hardware exists.
An in-network model may be weaker and slower than the frontier route. Complex work may need earlier handoff and the $500 ceiling becomes a GPU-hour budget. The source references LLM Inference Serving for batching and failover and the air-gapped case for disconnected environments. Those chapters are outside this capture.
| Data class | Allowed destination | What the gateway does |
|---|---|---|
| No PII, public content | Any approved provider | Normal routing and fallback |
| PII that can be masked | Any approved provider, after masking | Mask before the request leaves the network, not only on output, as the source's FDE track puts it |
| PII bound to a region | A provider endpoint in that region with contractual no-retention, or a model in the customer's VPC | Route only to that region's pool |
| Data that cannot leave the network | A self-hosted model inside the customer's VPC | Route only to the in-network pool |
Residual failure modes and next changes
Prepare five residual failures: an injection that defeats both guards, correlated provider degradation, hidden quality loss from pacing, stale cached answers and PII leaking through logs. Each needs its own observation and recovery, as the table shows.
Extend output policy to tool calls and grant tools least privilege after an injection incident. Choose an independent third provider or an internal model for shared-upstream failures. Alert on pacer changes and compare resolution by route. Include versions and invalidation in cache policy. After a leak, audit response, cache, trace and log paths rather than checking the answer alone. None of these additions proves the next attack or outage impossible.
| Failure | Why the design misses it | What to add next |
|---|---|---|
| A rephrased injection passes both guards | Both layers are probabilistic; the source calls injection defence "risk reduction, not a solved problem" | Output-side policy checks on tool calls, least-privilege tools, a red-team suite that grows with every incident |
| Both providers degrade together | They share a region, a cloud or an upstream dependency | A third, independent provider or an in-network model for the top intents |
| The pacer degrades quality silently | Routing tightens and nobody notices the answers got worse | Alert on pacer state; track resolution rate by route |
| A cached answer goes stale | The key lacked a document or policy version | Version-keyed cache with invalidation on document, ACL or metadata changes |
| PII leaks through logs, not responses | Output validation never sees the log pipeline | Redact at write time; audit logs, traces and cache after any leak, as the source's incident answer says |
Evidence and source limits
The complete captured case is Production LLM Gateway, retrieved 15 November 2026. It attributes the mock prompt, rubric, reliability patterns and cost guidance to its production and operations tutorial. Its further cross-case references are contextual pointers, not independently imported worksheets or chapters.
The source lists OpenAI API pricing and OpenAI moderation documentation, checked by the source on 27 September 2026. The former supports its historical GPT-4o mini $0.15/$0.60 and GPT-4o $2.50/$10.00 per-million illustration. The latter explains category scores and the flagged field. This offline rewrite preserves those attributions without asserting current availability or pricing.
Practice
Attempt the case before revealing the worked reasoning.
Attempt the design before reading answers
Start from a blank page. Reproduce the four constraints, clarify both gateway faces and define the latency measurement. Price the 30,000-turn day before choosing a provider. Draw admission, recovery, validation, cache and telemetry boundaries. Then simulate a region-bound provider outage and an exhausted daily budget.
The self-checks below come from the captured source. Each answer is native page content behind a reveal. The additional blank-page simulation above is authored practice. Reading progress records reading only. Mark practice attempts separately and use the rubric to assess reasoning.
Work through your answer
This local worksheet is a prototype addition. Notes save in this browser. Nothing is submitted or scored.
Check your reasoning
Reveal the self-assessment rubric
This checklist is an authored addition. Assess what you can explain without reopening the walkthrough.
0 of 7 reasoning checks covered.
Why must the gateway sit under the agent’s model calls, and not only in front of the customer’s message?
The source estimates 5 to 20 sub-requests per agent turn. An edge-only gateway misses later paid calls and cannot retry or fail over them. Route every model and evaluator call through the model face, while the edge face screens customer-facing input and output.
Price the day aloud.
14,700 × $0.00045 = $6.615 for simple turns. 6,300 × $0.0375 = $236.25 for five-call complex turns. Router $1.05 plus guards $1.35 gives $245.265, or about $245. Complex spend divided by total is about 96%. All rates and mix are historical illustrations.
What does the naive design cost?
Without cache or routing, all 30,000 turns make five large-model calls. Each turn costs 5 × $0.0075 = $0.0375. Daily cost is 30,000 × $0.0375 = $1,125, which divided by $500 is 2.25.
Why does the input guard run before the cache?
It blocks known injection attempts and masks PII before lookup. The key therefore uses masked text. Output validation must also pass before writing a response, preventing a blocked answer from being reused.
Why is a class named SemanticCache in the source not semantic?
It hashes normalised text into exact keys. The two Python paraphrases have different hashes and miss. Semantic lookup needs embeddings, a similarity search and a tuned threshold, while still enforcing permission, version and freshness boundaries.
What is the difference between a per-request cap and the pacer?
The cap rejects one oversized call before spending. The pacer watches the day’s accumulated spend. At 80% it tightens expensive routing, at 95% it permits the small route and complex handoff, and at 100% it permits only cache and handoff. Provider usage reconciles the ledger after each admitted call.
Order the resilience chain and say what each link handles.
Retry handles a transient blip with deadline-bounded jittered backoff. A breaker wraps retried calls and remembers an unhealthy provider. Fallback chooses another policy-allowed provider. Degradation supplies labelled customer help or handoff after no provider remains. The model face returns a typed failure.
Why does the model face return a typed error rather than a degraded string?
An agent could treat an approximate degraded reply as reliable model state and issue a refund or booking at a stale price. The typed error forces the workflow to handle failure explicitly. A human can receive labelled degradation or a ticket handoff at the edge.
Sum the common-path latency.
Using upper estimates, 1 ms rule guard + 10 ms cache + 400 ms router + 2,000 ms model + 1 ms validator = 2,412 ms, about 2.4 s. A 300 to 500 ms output check raises this toward 2.9 s. These stage estimates require end-to-end measurement before making a p95 claim.
Why can p95 full-answer latency never be under 3 s here?
Under the stated five-sequential-call assumption, complex turns take 5 to 10 s and form 21% of all turns. The fastest 79% cannot cover the 95th percentile. Agree first-token measurement for multi-step turns, or change the workflow/mix rather than promise an impossible full-answer SLO.
Why can’t a typical retry schedule run on the interactive path during an outage?
The waits 0.3 + 0.6 + 1.2 total 2.1 s before attempt four, excluding failed-call timeouts. Use a request deadline, retry only with sufficient remaining time, and let an open breaker skip the failed primary. Failover must still fit within that deadline.
A region-bound customer’s primary provider goes down. Where does traffic go?
Choose another endpoint in the same allowed region or a permitted in-network replica pool. If neither can answer, hand off. The global pool remains forbidden. Apply the same restriction to traces, cache and logs.
What is the cost card’s 60-second line?
Complex agent turns dominate spend at 96% of the illustrative total. Route fewer suitable turns there, cap agent steps and use a one-call workflow for common intents. Cache only safe answers. Measure cost per resolved conversation and resolution by route, since reducing per-request cost can increase failed or repeated conversations.
Self-assessment and level calibration
Use the source's seven criteria in the first table. Each asks for an observable explanation: the concrete resilience chain, cost controls before calls, separate rule and LLM guards, both input and output checks, replayable telemetry, a latency sum and a volunteered failure mode. The second table distinguishes levels by how constraints interact.
A senior answer supplies the mechanisms and prices the day. A staff answer resolves the five-call latency, deadline and streaming collisions, separates both faces and adds pacing. A principal answer constrains fallback by residency, plans the shared function-to-model layer and acknowledges the weaker internal model's GPU-hour budget. Real traffic, complexity mix and residency determine whether the illustrative ceiling remains valid.
| Source rubric criterion | Answered in |
|---|---|
| Names a concrete resilience chain (retry → circuit breaker → fallback → graceful degradation), not just "add retries." | Topics recovery |
| Puts cost control before the model call (routing + cache + budget), not as an afterthought. | Topics pricing, safe caching, metering |
| Separates rule-based guardrails (fast, free, first) from an LLM-as-guardrail layer (slower, catches rephrased attacks). | Topics guardrails |
| Covers both input and output PII/injection checks, not just input. | Topics guardrails |
| Names what gets logged/traced and why (cost per request, which model answered, guardrail decisions); enough to debug a bad run after the fact. | Topics tracing |
| States a concrete latency budget breakdown, not just "keep it fast." | Topics latency |
| Volunteers the failure mode of their own design (what still breaks, and what they'd add next). | Topics residency, failure review |
| Level | Sounds like | Missing |
|---|---|---|
| Senior | Names the full chain of retry inside a breaker, warm fallback and labelled degradation, runs rule-based guards before the LLM guard in both directions, and caps each request before the paid call. Prices the day at about $245 against $500 and sees complex turns carry 96% of spend. | The collisions: a five-call agent path cannot finish in 3 s, retries overrun the budget during an outage, and the LLM output check fights streaming. |
| Staff | Splits the gateway into an edge face and a model face, holds agent turns to first token under 3 s, runs router and input guard in parallel, and gives retries a deadline instead of an attempt count. Adds a pacer that tightens routing at 80% and 95% of spend, version-keyed cache entries, and one trace per request with cost, model and guard decision. | What happens when data cannot leave the region, and which other agents will route through this gateway next. |
| Principal | Makes residency a routing rule with its own in-region fallback pool, because a fallback across the boundary is a breach, not a recovery. Positions the gateway as the shared function-to-model layer for every agent, and says plainly that a self-hosted pool turns the $500 into a GPU-hour budget on a weaker model. | The real traffic, complex-turn share and residency policy, which decide whether $500 still holds past about 61,000 turns a day. |
Rehearse the 45-minute delivery
Use the source timing plan below. Spend the opening on scope and measurement, then show the dollar calculation before the architecture. Close by naming remaining failure modes. Rehearse with a timer rather than using reading progress as evidence of interview fluency.
Spoken-answer example for the two-minute close: “I would put an edge face around customer input and output, and a model face under every agent call. Cheap rules and PII masking run first. A small-model guard checks surviving intent, and output validation protects what reaches the customer. Each paid call gets a token and daily-budget admission, then a capable route with retry inside a breaker and a warm, allowed fallback. Both providers down means labelled customer degradation or handoff, while the agent receives a typed failure. Under this case’s assumptions the day costs about $245, and complex turns account for about 96%. The common path fits the whiteboard latency sum, but the agent path needs first-token measurement and retries need a deadline. A trace records cost, model and guard decisions. Region restrictions constrain the fallback and telemetry too.”
| Minutes | What to say |
|---|---|
| 0 to 5 | The two faces; the five questions; state the assumptions |
| 5 to 10 | Requirements with numbers; what 3 s measures |
| 10 to 15 | Price the day: about $245, 96% on complex turns, ceiling near 61,000 turns |
| 15 to 25 | The diagram: screen, meter, route, recover |
| 25 to 30 | Guardrails both directions; cache keys |
| 30 to 37 | The resilience chain and the latency sums |
| 37 to 42 | Observability and residency |
| 42 to 45 | What still breaks, and the cost pivot |
Answer the over-budget pivot
For the source's ten-minute cost pivot, measure spend by route and prompt version before changing the entire fleet. The dominant driver is the five-call large-model path: 21% of turns and 96% of cost. Retries can add spend during incidents.
Then route suitable work to the small model and common intents to deterministic one-call workflows. Bound steps, tokens and daily pacing. Cache safe FAQs with permission and version keys. Trim system prompts and history where evaluation permits. This sequence preserves high-value paths instead of downgrading every request indiscriminately.
Prove savings with cost per resolved conversation, spend by route, complex share, hit rate and resolution by route. A cheap response that causes a failed support conversation or repeated attempts may increase total resolution cost. Never cache account-specific answers to improve the headline hit rate.
| Dominant driver | The large-model agent path: 21% of turns and 96% of spend, then retries during incidents |
| Cheapest lever first | Tighten the router threshold on labelled traffic; send common intents to a one-call deterministic path; cap agent steps; cache safe FAQ answers; trim the system prompt and history |
| Metric that proves it | Cost per resolved conversation; spend by route; complex-turn share; cache hit rate; resolution rate by route |
| Do not | Downgrade every request to the small model, or cache account-specific answers to raise the hit rate |
| 60-second line | Almost all the money is the complex agent path, so route fewer turns there, cap its steps, and send common intents down a one-call path. Cache only answers the key proves are safe. Prove it with cost per resolved conversation, not cost per request. |
Return to the decisions you could not explain.
Review the essentialsQuick review
Recall the decisions, failure responses, and closing answer.
Recall the admission and recovery boundaries
The edge face protects customer-facing input and output. The model face sees every one of an agent's 5 to 20 potential sub-requests. Screen, meter, route and recover, with a trace across every step.
Under the captured assumptions, 30,000 turns become 9,000 cache hits, 14,700 small calls and 6,300 five-call large turns. Spend is about $245 against $500. Complex work consumes about 96%. A 40% complex miss share raises it to about $323, and the unchanged mix binds near 61,000 daily turns.
Rules precede paid intent checks. Exact cache lookup starts with masked text and tenant, permission, document and prompt versions. Semantic lookup requires embeddings and a threshold. Validate outputs before cache writes. Admit calls before spending, pace at 80%, 95% and 100%, then reconcile usage.
Retry handles a blip, a breaker remembers bad dependency health, fallback selects another permitted provider and degradation supplies the human-facing floor. Machines receive typed errors. The illustrative breaker trips at three failures, probes after five seconds and needs half-open recovery. Keep fallback prompts, tools and quota usable.
The common-path sum is about 2.4 s, risky output about 2.9 s and serial input plus output checks about 3.4 s. Run independent input checks in parallel. Five-call turns need first-token measurement. Deadline-bound retries and buffered risky output prevent misleading latency claims.
Trace cost, usage, actual model and provider, prompt version, guard reason, cache, tools, retries, timeouts and outcome. Redact before writing and retain within the same allowed region. Restricted pools need restricted fallback. In-network models turn token spend into GPU-hours and may need earlier handoff.
Close the design by naming residual injection, correlated providers, pacing quality drift, stale caches and log leaks. For an over-budget pivot, measure, route, bound and cache safely. Validate the result with cost per resolved conversation.