Production LLM Gateway
Screen, meter, route and recover support traffic inside competing cost, safety and latency constraints.
- Kind
- Case study
- Level
- Core
- View
- Interview prep
- Sections
- 4
- By
- Sourav Banerjee
- Last updated
- 21 Nov 2026
Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.
Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.
Case brief
The case in one line: one shared path for every model call of a support agent, which screens, meters, routes and recovers each call under four hard constraints.
30-Second Cheat Sheet
- The product: a gateway for a customer-support agent. All model traffic passes through it.
- Constraint 1, availability: survive a provider outage with no customer-visible downtime.
- Constraint 2, safety: resist prompt injection and PII leaks.
- Constraint 3, cost: spend less than $500 per day.
- Constraint 4, latency: keep p95 below three seconds.
- The first discovery question: what counts as finishing, the first streamed token or the complete answer?
- The trap: one customer message can trigger an agent turn with several model and tool steps. Screening only the message leaves later paid calls outside budget and recovery.
- The numbers are historical whiteboard inputs from the captured case, not current vendor offers.
1. Four Constraints on Every Support Turn
The task
Design a gateway for a customer-support agent that:
| Constraint | Target |
|---|---|
| Availability | Survives a provider outage without customer-visible downtime |
| Safety | Resists prompt injection and PII leaks |
| Daily spend | Less than $500 per day |
| Latency | p95 below three seconds |
p95 = 95% of the measured requests finish within that time.
PII (personally identifiable information) = anything that identifies a person: name, email, phone, account number.
- Ask first: what counts as finishing? The first streamed token or the complete answer?
The terms that carry the whole case
| Term | Meaning |
|---|---|
| Gateway | The shared path through which model traffic passes. It screens, meters, routes and recovers each call. |
| Agent turn | What one customer message may trigger: several model and tool steps |
| Screening only the message | Leaves the later paid calls outside the budget and recovery controls |
Who it's for
- Engineers preparing for Forward Deployed, solutions and applied AI interviews.
What it assumes you know
- Model APIs
- Token pricing
- API gateways
- Retries and circuit breakers
How to use it
- Work the dollar arithmetic before reading the solution.
- Then rehearse the design and the cost pivot (both in the full casebook's Practice section).
- The target is an explainable design, not a deployed gateway.
Where the case comes from
- 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 get further worked treatment in this casebook.
The caveat on every number
- All model names, prices, durations and traffic assumptions 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.
The core idea (overview figure)
request → safe cache hit?
- Yes → bypasses metering and generation.
- No → budget admission → complexity routing → recovery.
2. Trace a Support Request
The request (illustrative): a customer asks a support question that includes an account number.
- Authenticate. Authentication identifies the session. Policy assigns its data class.
- Mask. The input guard masks PII before cache lookup or any provider call.
- Cache.
- 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.
- Checks intent.
- Route.
- A simple turn takes a small-model route.
- An agent turn may make five calls, each admitted and metered through the model face.
- Recover. A failed provider moves the request to an allowed fallback, only while time and budget remain.
- Result for the customer, one of three:
- A validated answer with its model source.
- A labelled degraded response.
- A human handoff.
- Result for an agent: a typed failure when no trustworthy model response is available.
- Every paid call in that trace is admitted and metered, not only the first one.
Quick Recall: Lines to Say in the Interview
- "First question: does three seconds mean first token or full answer?"
- "One customer message can become several paid model calls, so the gateway sits under every one of them."
- "Screen, meter, route, recover."
- "PII is masked before the cache and before any provider sees it."
- "Live account answers never go in a reusable cache."
- "The customer gets an answer, a labelled degraded reply or a person. The agent gets a typed failure."
- "These prices are historical whiteboard inputs, not a current offer."
Design walkthrough
The goal: a gateway that sits on both sides of a support agent, turns each constraint into a test, prices the day at about $245 against $500 and names which component owns each failure.
30-Second Cheat Sheet
- Two faces: the edge face screens customer input and final output. The model face sits under every agent or evaluator call.
- Why both: one user request can become 5 to 20 sub-requests. Edge-only budgeting misses most of the spend.
- Ask five questions before drawing. Assume 10,000 users a day, 3 turns each, one customer in several regions.
- Every constraint fails a test: zero customer-visible errors in a single-provider outage, p95 under 3 s, under $500/day, an 8,000-token input cap.
- The day costs about $245 (49% of budget). Complex turns are 21% of traffic and 96% of spend.
- Naive design: $1,125, or 2.25× the cap.
- Fourteen components, each with a fails how column: closed, degrades or rolls back.
- Validate on the real path with the versioned red-team suite before shipping configuration.
1. Place the Gateway on Both Sides of the Agent
The two faces
| Face | Where it sits | What it does |
|---|---|---|
| Edge face | Between the customer and the agent | Screens customer input and final agent output |
| Model face | Between every agent or evaluator call and its provider | Admits, meters, routes and recovers each call |
- The source playbook estimates one user request can become 5 to 20 sub-requests.
- Edge-only budget enforcement therefore misses most of an agent's spend.
- It also leaves later failures unrecovered.
The shared function-to-model layer
- One source-reported research platform uses a shared sidecar.
- Agents ask for a function. Configuration maps that function to a provider.
- When a provider changes, the team changes one mapping, not provider code in five places.
- This is the shared function-to-model layer a platform can extend to further agents.
Not the action gateway
- The action-authorisation gateway 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.
- This model traffic gateway does not grant refund or booking authority.
Ask the five questions before drawing
| 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 can't 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; the residency deep dive covers both cases |
| What must never happen? | Sets which checks fail closed | PII leaks to a customer or a provider it shouldn't reach |
- Residency stays an explicit discovery question.
- Use first token for multi-step turns and full answer for one-call turns only after agreeing that reading with the interviewer.
Fail closed = when the check can't decide, it blocks rather than lets traffic through.
2. Make Each Constraint Fail a Test
- Turn each requirement into a test and assign an owning component.
Availability, latency and spend
- During a single-provider outage, every customer response is answered, labelled as degraded, or handed off.
- A useful availability test.
- It doesn't establish that every outage can produce an equivalent model answer.
- Latency: p95 under three seconds to first token on every turn, and to full answer on one-call turns.
- Daily spend: enforce the $500 ledger before admission.
- Per-call cap: the illustrative input cap is 8,000 tokens. Reject an oversized call explicitly, never silently truncate context.
Injection, PII and replay
- Version the red-team suite. Block release when a known attack passes input or output checks.
- This is a finite regression requirement.
- It can't establish zero residual injection risk.
- Apply PII policy to responses and logs.
- Tag every answer with model and provider.
- Retain enough trace to reconstruct guard decisions, route, tokens and cost.
What makes these operable
- Safe caching, region routing, real-path red teaming and versioned configuration.
Constraints stated so they can fail
| 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 |
Who enforces each requirement
| 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 |
Soundbite: "A requirement that can't fail a test is a preference. Each of these has a test and an owner."
3. Calculate the $500 Day
The traffic model
- 30,000 turns a day = 10,000 users × 3 turns.
- 30% cache hit rate removes 9,000 generation paths.
- Of the 21,000 misses:
- 70% simple: one call to the small model.
- 30% complex: five calls to the large model.
- Five calls is the low end of the source's 5 to 20 sub-request rule.
- Each call: 2,000 input and 250 output tokens.
- The flat 2,000 assumes bounded context per step. If every step re-sends the conversation plus earlier tool results, input tokens climb step by step.
- Measure per-step growth before trusting the complex-turn price.
Unit costs
- Small model at $0.15 in and $0.60 out per million tokens:
(2,000 × 0.15 + 250 × 0.60) / 1,000,000 = $0.00045per call.
- Large model at $2.50 in and $10.00 out:
- $0.0075 per call.
- Five calls: $0.0375 per complex turn.
The total
- Simple: 14,700 turns × $0.00045 = $6.615, shown as $6.62 in the table.
- Complex: 6,300 turns × $0.0375 = $236.25.
- Router: 21,000 classifications × $0.00005 = $1.05.
- Guards: 15,000 input checks × $0.00005 + 6,000 output checks × $0.0001 = $1.35.
- Total: $245.265, reported as about $245, or 49% of budget.
- Cache hits cost no generation tokens here, but still need gateway infrastructure and safety processing.
Sensitivity
| Change | Result |
|---|---|
| No caching or routing (30,000 five-call large-model turns) | $1,125, or 2.25× the cap |
| Complex share | 21% of all traffic, about 96% of modelled spend |
| Complex share of misses 30% → 40% | Daily spend rises to about $323 |
| All rates and proportions held constant | $500 buys roughly 61,000 turns |
- 61,000 is a sensitivity estimate, not a capacity promise.
Assumptions
| 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 |
The bill
| 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 |
Soundbite: "About $245 a day against $500, and 96% of it is the five-call agent path."
4. Trace Components and Failure Ownership
One system, many diagrams
- The source diagrams show the same request path in several arrangements, with a versioned control plane above it.
- Read them as one system, not 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 rolls back atomically. Half the workers must never sit on unsafe policy.
The input path
authenticate → rule guard masks PII → cache lookup → token check → router ∥ LLM intent guard
- Auth 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 picks a capable model and defaults to a safe route on failure.
- The LLM intent guard may be skipped only for policy-approved low-risk, previously seen patterns.
The model face
spend ledger and pacer → provider A (retry inside breaker) → provider B → typed failure
- Every agent call reaches the spend ledger and pacer.
- Adapters wrap providers in deadline-bounded retry and a breaker.
- If A fails, B gets a portable prompt and tool schema.
- If both fail, the edge responder labels degradation or hands off.
The output path
rule validator (PII, banned content) → semantic check on risky replies → release → cache write
- Output rules always validate PII and banned content.
- A semantic check runs for risky replies.
- A cache write happens only after output validation passes.
Screen, meter, route, recover
- The phrase names responsibilities. It isn't permission for an unmetered router or guard call.
- All paid classifier, guard, retry and fallback calls need admission too.
- Telemetry writes asynchronously: request traces, metrics, JSON events, cost tags and model tags.
Components and how each fails
| # | Component | Responsibility | Fails how |
|---|---|---|---|
| 01 | Auth and rate limit | Identifies 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, 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; 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 |
Circuit breaker = a wrapper that remembers a provider is unhealthy and rejects calls to it at once instead of waiting on timeouts.
5. Validate Before Shipping Configuration
Test the real path
- Exercise the actual authenticated endpoint, rate limits and guard path with the versioned red-team suite.
- Primary outage.
- Fallback quota exhaustion.
- Both providers unavailable.
- Cache outage.
- Each budget threshold.
- A region-bound request never escapes its pool, including during recovery.
- A model-face typed failure can't be mistaken for a successful tool response.
Measure what matters
- Compare routing cost with misrouting and resolution rate on labelled traffic.
- Measure first-token and full-answer latency separately, by route.
- Test PII redaction in cache, responses, logs and traces.
- Replay a bad run: it must identify the prompt version, guard reason, selected model, retries and final outcome.
Ship as configuration
- Ship prompts, policy and routes as versioned configuration with rollback.
- Keep the fallback warm with the source's illustrative 1% live traffic share.
- Verify the fallback can accept full-load quota before an outage.
- This validation and rollout sequence is an authored synthesis of the source's tests and control-plane requirements.
Quick Recall: Lines to Say in the Interview
- "The edge face screens the customer; the model face sits under every agent call, because one request can become 5 to 20."
- "This gateway routes model traffic. It doesn't grant refund or booking authority."
- "30,000 turns, about $245 a day, 49% of the budget, and 96% of it is complex turns."
- "Without caching or routing it's $1,125, two and a quarter times the cap."
- "Reject an oversized call explicitly; never truncate silently."
- "A cache outage is a miss, never an error."
- "Validate output before writing the cache, so a blocked answer never becomes a hit."
- "A bad config rolls back atomically. It never half-applies."
- "Keep the fallback warm at 1% and prove it takes full-load quota."
Technical deep dives
What this part covers: the mechanisms behind follow-up questions. Guards, caching, metering, recovery, the latency budget, tracing, residency, residual failures and the source's limits.
30-Second Cheat Sheet
- Rules first, LLM guard second: rules are microseconds and free; a small-model guard catches paraphrased attacks for money and a few hundred ms.
- A moderation pass isn't a product-policy pass.
- Exact cache first. Semantic needs embeddings and a tuned threshold. Never cache live account answers.
- Cap one request, pace the day: tighten at 80%, small model only at 95%, cache and handoff only at 100%.
- Retry → breaker → fallback → degradation, all under a request deadline. The agent gets a typed error.
- Latency: common path about 2.4 s, plus output check about 2.9 s, plus a serial input guard about 3.4 s (breaks).
- Trace without copying PII: redact before writing, write async.
- Residency constrains the pool before failover. Falling back to a global pool is a breach, not a recovery.
1. Rules, Intent Checks and Streaming Boundaries
Two kinds of input guard
| Guard | Checks | Cost | Blind spot |
|---|---|---|---|
| Rules | Regex patterns, length, schemas, banned phrases | Microseconds, no per-model-call bill | Can't recognise every paraphrase |
| Small-model guard | The intent of the surviving text | Money plus a few hundred milliseconds | Still probabilistic |
- Example from the source: "pretend the rules above never existed" may evade literal injection patterns. The small-model guard can recognise that rephrase.
Check both directions
- Mask the customer's PII before forwarding input.
- Validate output, because a model can repeat something the customer supplied two turns earlier.
- A clean current input can't prove the conversation history is safe to disclose.
Moderation isn't product policy
- Moderation applies a fixed general harm taxonomy: harassment, hate, self-harm, sexual content and violence.
- Category scores determine flags.
- The source reports that mild rudeness, "you are very poor ha ha", passed its moderation test.
- Product guardrails separately enforce support scope and system-prompt secrecy.
- A moderation pass doesn't mean a product-policy pass.
Blocks, red teaming and residual risk
- 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, never a zero-risk promise.
Soundbite: "Rules are fast and free, so they run first. The LLM guard catches the rephrase. Neither makes injection a solved problem."
2. Exact and Semantic Caching Have Different Mechanisms
| Cache | Mechanism | Paraphrases | Risk |
|---|---|---|---|
| Exact | Normalise the PII-masked query, hash it into a key | "What is Python?" and "Tell me about Python" miss each other | Low |
| Semantic | Embed the query, search nearby stored vectors; a tuned similarity threshold decides reuse | Can match | A loose threshold returns mismatched or stale answers |
- A class called
SemanticCachethat only hashes text still implements exact matching. - Start exact. Add vector lookup only when observed traffic has enough repeated paraphrases to justify its risk and operating cost.
What goes in the key
- Tenant, user permission, document version and prompt version.
- Cache reusable FAQ responses, never live account answers.
Why masking makes the rule necessary
- "What is the balance on [ACCOUNT]?" from two customers masks to the same text and the same key.
- Cacheability must come from the request's data class and intent, decided before lookup, not from the key alone.
Invalidation
- Changing a prompt or knowledge version deliberately invalidates prior entries.
- Invalidate on document, ACL or metadata changes.
- Freshness and permission checks still apply to semantic hits.
ACL (access-control list) = the list of who may see or change a thing.
Operating it
- A sudden hit-rate drop: inspect keying, versioning, traffic mix and invalidation before adding capacity.
- Output validation precedes writes: a blocked answer must never become a future cache hit.
3. 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 the threshold on labelled real traffic.
- Simple sent to the large model → wasted money.
- Complex sent to a weak route → lower resolution.
- Compare the cost saving with the product's tolerated misrouting rate.
Cap one request, meter the day
- 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.3andlen(text.split()) × 4 // 3are trend approximations, not reliable admission accounting.
The pacer responds before exhaustion
- At 80% spent: tighten routing toward cheaper paths. Here "raise the router threshold" means require stronger evidence before taking the expensive route.
- At 95%: allow the small model; hand complex work to humans.
- At 100%: cache and handoff only.
- A plain hard cap that runs out at 4 p.m. can't meet the customer availability goal.
| 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 | 80%: raise the router threshold; 95%: small model only plus human handoff for complex turns; 100%: cache and handoff only |
Concurrency caveat (added by the teaching design, not the source)
- Concurrent calls need atomic budget reservations for their bounded potential cost, then 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 doesn't supply this concurrency protocol.
4. Retry, Breaker, Fallback and Degradation
| Link | Handles | Key rule |
|---|---|---|
| Retry | A transient connection drop or provider rate limit | Exponential backoff with jitter, under a request deadline |
| Breaker | Remembers dependency health | Closed → open → half-open probe → closed |
| Fallback | Retries exhausted or breaker open | An independent, policy-allowed provider with portable prompts and tools |
| Degradation | Neither provider can answer | Labelled reply or ticket at the edge; typed error at the model face |
Retry
- Jitter spreads clients across time. Fixed intervals synchronise retries into a thundering herd.
- A provider 429 with a Retry-After header: treat that wait as the floor for the next attempt.
- Fail over at once if it exceeds the request's remaining deadline.
- The source's general pattern allows three to four attempts. Interactive requests obey a deadline instead.
Jitter = a random offset added to each backoff wait so clients don't retry in lockstep.
Breaker
- Wraps the retried provider call.
- Illustrative settings:
failure_threshold=3,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 stop a different tool-calling format from silently breaking the agent.
- Keep the backup warm, verify quota at full load, and tell provider 429s apart from your own gateway limits.
Degradation
- At the edge: a labelled response seeded from safe cached context, or a ticket for a person.
- At the model face: a typed error.
- A degraded prose string passed to an agent as a real answer can cause a refund or booking against stale information.
- Recovery also obeys residency and spend policy.
Soundbite: "Retry handles a blip, the breaker remembers, fallback picks another allowed provider, and degradation is the floor. Machines get typed errors."
5. Three Collisions Inside the Three-Second Target
The stage estimates
| Stage | Source estimate |
|---|---|
| Rule guard | ~1 ms |
| Cache | 5 to 10 ms |
| Router | 200 to 400 ms |
| Main model | 1 to 2 seconds |
| Output rules | ~1 ms |
- Upper ends:
1 + 10 + 400 + 2,000 + 1 = 2,412 ms, about 2.4 seconds. - Whiteboard durations, not measured percentiles. Summing stage estimates doesn't establish an end-to-end p95.
Collision 1: guards in series
| 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 |
- Router and input guard read the same masked input, so run them in parallel. Their cost becomes the slower of the two.
- Skip the LLM input check only for policy-approved low-risk, previously seen patterns.
Collision 2: five-call agent turns
- Five sequential calls at 1 to 2 seconds = 5 to 10 seconds.
- Complex turns are 21% of traffic, so p95 full-answer latency lands inside the slow population.
- Agree first-token measurement for agent turns.
- Parallelise independent read-only tool work.
- Send common intents through a one-call workflow or router where an agent adds no value.
Collision 3: retries
- 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.
The streaming boundary
- A validator can't retract words already displayed.
- The same applies to recovery: if the primary fails after tokens reach the customer, the fallback can't silently continue the sentence from a different model.
- Discard the partial answer with a visible restart notice, or hand off.
- Record both providers on the trace.
- Run rule checks sentence by sentence before release.
- Buffer risky replies (refunds, account data) until the LLM output check finishes.
- Reconcile buffering with the first-token target. Don't claim both unconditional streaming and complete pre-display semantic review.
6. Trace Enough State Without Copying PII
Three tools, three jobs
- Structured logs explain one request.
- Metrics count outcomes across traffic.
- Traces identify the stage that caused a silent wrong answer.
- A successful HTTP status isn't evidence of a correct support response.
Trace fields
| Group | Fields |
|---|---|
| Source 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, final outcome |
| Added by the gateway | Provider, guardrail decision, block reason |
- Retrieval fields apply only when a request actually uses retrieval. Not 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, write asynchronously.
- Synchronous logging can cause a post-deploy latency jump.
- Restricted requests need equally restricted traces, including their storage backend.
The six-signal dashboard
- Daily spend against the pacing line
- p95 first-token latency
- Fallback rate by provider
- Breaker state
- Guard block rate by rule
- Cache hit rate
| Change | Start the investigation with |
|---|---|
| Spend | Route and prompt version |
| Hit rate | Key, version, traffic and invalidation |
| Fallback | Provider health, quota and breaker decisions |
- The source points to Observability and Production Diagnosis for replay and cost-spike investigation. Those chapters weren't captured here.
7. Constrain the Provider Pool Before Failover
The open gap
- The underlying tutorial 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.
VPC (virtual private cloud) = the customer's isolated cloud network.
Data class decides the pool, before routing
| 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 | An in-region provider endpoint with contractual no-retention, or a model in the customer's VPC | Route only to that region's pool |
| Data that can't leave the network | A self-hosted model inside the customer's VPC | Route only to the in-network pool |
- At the edge, policy and PII findings assign the data class.
Each restricted pool gets its own recovery
- 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's worked tracing examples are hosted, leaving a self-hostable backend as implementation work.
Self-hosting turns tokens into GPU-hours
- Source sizing formula:
Replicas = ceil((QPS × Tokens_request) / (TokensPerSecond_replica × UtilizationTarget))
- QPS × tokens per request = token throughput demand.
- Divide by sustainable throughput per replica at the target utilisation, then round up.
- If the count exceeds available hardware, reduce or reshape the workload. Don't assume more hardware exists.
The cost of staying in-network
- An in-network model may be weaker and slower than the frontier route.
- Complex work may need earlier handoff.
- The $500 ceiling becomes a GPU-hour budget.
- The source references LLM Inference Serving (batching, failover) and the air-gapped case (disconnected environments). Both are outside this capture.
Soundbite: "A fallback across the residency boundary is a breach, not a recovery."
8. Residual Failure Modes and Next Changes
- Prepare five residual failures. Each needs its own observation and recovery.
| 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 |
- After a leak, audit response, cache, trace and log paths, not the answer alone.
- None of these additions proves the next attack or outage impossible.
9. Evidence and Source Limits
- The captured case: 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 cross-case references are contextual pointers, not imported worksheets or chapters.
- OpenAI API pricing and OpenAI moderation documentation, checked by the source on 27 September 2026.
- Pricing supports the historical GPT-4o mini $0.15/$0.60 and GPT-4o $2.50/$10.00 per-million illustration.
- Moderation docs explain category scores and the flagged field.
- This rewrite preserves those attributions without asserting current availability or pricing.
Quick Recall: Lines to Say in the Interview
- "Rules run first because they're free; the LLM guard catches the rephrase."
- "A moderation pass isn't a product-policy pass."
- "A class named SemanticCache that only hashes text is an exact cache."
- "Two customers' masked balance questions share a key, so cacheability is decided by data class before lookup."
- "Pace at 80, 95 and 100 percent, because a hard cap that runs out at 4 p.m. fails availability."
- "0.3 plus 0.6 plus 1.2 is 2.1 seconds before attempt four, so retries get a deadline."
- "About 2.4 seconds on the common path, 2.9 with the output check, 3.4 if the input guard runs in series."
- "Redact before writing; restricted requests get restricted traces."
- "Self-hosting turns the $500 into a GPU-hour budget on a weaker model."
Quick review
One sentence: screen, meter, route and recover every model call on both faces of the agent, price the day at about $245 against $500, and name what still breaks.
30-Second Cheat Sheet
- Two faces: the edge face guards customer input and output; the model face sees every one of 5 to 20 potential sub-requests.
- The day: 30,000 turns, about $245 against $500, 96% on complex work.
- Cache safely: masked text plus tenant, permission, document and prompt versions. Validate before writing.
- Pace: 80%, 95%, 100%, then reconcile usage.
- Recover: retry → breaker → fallback → degradation. Machines get typed errors.
- Latency: 2.4 s / 2.9 s / 3.4 s. Parallel input checks; first-token measurement for five-call turns.
- Residency: restricted pools need restricted fallback; in-network models turn spend into GPU-hours.
- Close with five residual failures and the cost pivot.
1. Recall the Admission and Recovery Boundaries
Faces and the rule
- Edge face: protects customer-facing input and output.
- 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.
The numbers under the captured assumptions
| Item | Value |
|---|---|
| Turns a day | 30,000 |
| Cache hits | 9,000 |
| Small calls | 14,700 |
| Five-call large turns | 6,300 |
| Daily spend | About $245 against $500 |
| Complex share of spend | About 96% |
| Complex miss share at 40% | Spend rises to about $323 |
| Where the unchanged mix binds | Near 61,000 daily turns |
Guards, cache and admission
- Rules precede paid intent checks.
- Exact cache lookup starts with masked text plus 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.
The recovery chain
| Link | Job |
|---|---|
| Retry | Handles a blip |
| Breaker | Remembers bad dependency health |
| Fallback | Selects another permitted provider |
| 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.
Latency
| Path | Sum |
|---|---|
| Common path | About 2.4 s |
| Risky output | About 2.9 s |
| 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 and residency
- 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
- Name the residual failures: residual injection, correlated providers, pacing quality drift, stale caches and log leaks.
- Over-budget pivot: measure, route, bound and cache safely.
- Validate the result with cost per resolved conversation.
Sixty-second cost line (from the full casebook's cost pivot): "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."
Flashcard Drill
Quick Recall: Lines to Say in the Interview
- "The model face sees every one of the agent's 5 to 20 sub-requests."
- "Screen, meter, route, recover, with one trace across every step."
- "About $245 against $500, and 96% of it is complex work."
- "Rules before paid intent checks; validate before the cache write."
- "Pace at 80, 95 and 100 percent, then reconcile against provider usage."
- "Retry handles a blip, the breaker remembers, fallback picks a permitted provider, degradation is the floor."
- "2.4, 2.9, 3.4 seconds: so the input checks run in parallel."
- "Restricted pools need restricted fallback."
- "Prove the pivot with cost per resolved conversation."
Where next
- Revise the concepts