Skip to content
Tech Interview Prep
Technical interview guide

Model Serving & Inference Infrastructure

The infrastructure choices behind getting predictions out of a trained model at production latency and scale.

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

Scope: NVIDIA Triton, KServe, Kubernetes autoscaling, Amazon SageMaker inference, and NIST AI RMF guidance current 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-2

Choose among real-time, asynchronous, batch, and streaming inference.

Answer

What I'd say first

Assume a fraud model on card authorizations: 2,000 req/s peak, a 100 ms p99 budget, features from a 5-minute sliding window, and a nightly retrain. The mode is decided by two questions: does the caller block on the answer, and how stale may the inputs be?

  • Real-time (synchronous) when the caller blocks: auth, ranking, ad selection. The budget is end-to-end p99, not GPU kernel time.
  • Asynchronous when the caller can wait seconds to minutes and needs a durable handle: LLM generation, document scoring, video. Return a job id, deliver by webhook or poll.
  • Batch when the input set is bounded and the schedule's staleness is acceptable: nightly scores for 40M users written to the feature store.
  • Streaming when each event must be scored as it arrives and the decision depends on state across events: velocity checks, session features, windowed aggregates.

Deciding criteria

CriterionReal-timeAsyncBatchStreaming
Freshnessmss–minup to schedule intervalms–s
Caller blocks?yesnonono
State across eventsnononoyes (keyed state, watermarks)
Cost per predictionhighest (peak-provisioned)mediumlowestmedium
Retry semanticscaller retries, must be idempotentat-least-once + idempotency keywhole-job rerunexactly-once via checkpoints

Worked sizing (hypothetical)

One A10G runs the model at 6 ms batch-1 and 30 ms at batch 32, so ~1,000 req/s per GPU. Triton with max_batch_size=32 and max_queue_delay_microseconds=5000. At 2,000 req/s peak you need 2 GPUs; at 50% utilization p99 ≈ 2 ms network + 5 ms queue + 3 ms preprocess + ~1 ms GPU + 2 ms postprocess ≈ 13 ms, well inside 100 ms.

Now the spike: 5,000 req/s needs 5 GPUs. With 2, the GPU is 2.5× oversubscribed, so the queue grows without bound: max_queue_delay_microseconds caps how long a request waits before batching, not the backlog behind it. p99 goes from 13 ms to seconds in roughly 10 s. Autoscaling on GPU utilization can't save you: a 15 s metric scrape plus 60–90 s node provisioning. You need admission control or load shedding at the edge, and a fallback rule-based decision.

Failure modes and detection

  • Real-time: pool saturation. Detect on Triton's nv_inference_queue_duration_us and deadline-miss rate, not GPU utilization: utilization sits at 100% long before p99 breaks.
  • Async: a poison message retried forever, duplicate side effects. Detect on DLQ depth and retry count; require an idempotency key on the job.
  • Batch: silent staleness. The 02:00 job fails, nobody notices, the store serves yesterday's scores. Detect with a freshness SLA: alert when now - max(event_time) exceeds 2× the schedule interval.
  • Streaming: backpressure. Consumer lag grows when input rate exceeds processing rate; detect on Kafka consumer lag and Flink checkpoint duration. State that grows unboundedly lengthens checkpoints and restarts; late events past the watermark are dropped, so decide drop-vs-update explicitly.

When a mode is wrong

Don't use real-time for anything a human doesn't block on: you pay peak-provisioning cost for idle GPUs. Don't use batch when the decision needs the last 5 minutes. Don't use streaming when the input is a bounded file; you inherit state, watermarks and checkpointing for nothing. Hybrid is normal, streaming features feeding a real-time model, but every path must serve the same versioned prediction contract, or the modes disagree on the same input.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Define the artifact and configuration lifecycle for serving.

Answer

What a strong candidate says first

An artifact is the immutable bundle that runs a model: weights, preprocessing code, tokenizer, runtime image, dependency lockfile. Configuration is the small mutable pointer that says which artifact version each environment runs. The lifecycle is build → register → promote → serve → retire, and the rule that makes it work: promote references to immutable artifacts, never rebuild per environment.

Assumptions: MLflow 2.x model registry (or SageMaker Model Registry), an OCI registry, Kubernetes, GitOps with Argo CD.

Build. Training writes weights plus a manifest; the registry records a SHA-256 of the artifact and provenance (git commit, dataset version, hyperparameters). The runtime image is built separately and referenced by digest: @sha256:..., never :latest. Both are signed with cosign.

Register. The registry assigns a version. MLflow 2.9 deprecated registry stages (Staging/Production) in favour of aliases and tags, so move an alias like champion rather than mutating a stage. The version links to the image digest, input/output schema, preprocessing, eval metrics, and approval record.

Promote. Only the pointer changes. In Git:

YAML
# envs/prod/serving.yaml
model:
  name: fraud-scorer
  version: "12"                                  # registry version, immutable
  image: registry.internal/serve@sha256:9f2c...  # digest, immutable
  alias: champion

Argo CD syncs that; the pod spec changes, nothing is rebuilt.

Serve. The pod pulls the referenced artifact, verifies the cosign signature, checks schema and runtime version, then loads. Verification runs at admission/pod start, not per request: it costs a one-off startup delay, not request latency. Expose the loaded version and checksum on /healthz so "what is running" is answerable without reading Git.

Retire. Keep N prior production versions (5 is a common policy) for rollback; archive beyond that to cold storage. Never delete a version still referenced by any environment.

Rollback trace (numbers illustrative). v12 ships and the error rate goes 0.4% → 5.2% over four minutes. On-call reverts the pointer:

git revert <sha> && git push
argocd app sync serving-prod
kubectl rollout status deploy/fraud-scorer

Argo CD applies the old digest; new pods start, verify, pass readiness. Recovery is bounded by pod startup (the image is already cached on the node, so seconds) not by a rebuild. The audit trail is Git history plus the registry's approval record.

Failure modes and detection

FailureSymptomDetection
Schema drift: model expects 10 features, config sends 12Garbage scores or 500sPre-load schema check; input-validation metric
Missing dependency in imageCrashLoopBackOffPod never becomes ready; rollout stalls
Signature verification fails (tampered artifact, rotated key)Load abortsAdmission denial event; alert
Rollback impossible: prior version GC'd or pointer overwrittenStuck on bad versionPeriodic rollback drill

Trade-offs. Immutability buys reproducibility and auditability; it costs a full build for a hotfix. Mutable tags are faster and lose the record of what production ran. Signature verification costs a startup step and key management; skip it in dev, not prod. If the model is single-tenant and low-risk you can run mutable tags, but the moment you need rollback or compliance, the immutable pointer is the baseline.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Design health probes for a model server.

Answer

First 90 seconds. Assume Kubernetes, one pod per GPU, weights pulled from object storage at container start, HTTP inference on :8000. The three probes answer three different questions, and collapsing them is the usual bug. Startup: has the model finished loading? Liveness: can this process still make progress? Readiness: should the Service send it traffic right now? A liveness probe that touches the model registry restarts every pod when the registry blips; a readiness probe that returns 200 as soon as the socket binds sends traffic to a pod with no weights. Keep liveness purely in-process, keep readiness about servability, and let startup absorb the long load.

Mechanism. The kubelet calls the probe on a timer. HTTP: any 2xx is success, anything else or a timeout is a failure. Exec: exit code 0 is success. gRPC (GA in Kubernetes 1.27): speaks the standard grpc.health.v1.Health/Check protocol, so a gRPC server needs no HTTP shim. failureThreshold consecutive failures flip the state; for liveness that means a container restart, for readiness it means removal from the Service's EndpointSlices. While a startup probe is running, liveness and readiness are disabled: that is the whole point of it.

Kubelet defaults are periodSeconds: 10, timeoutSeconds: 1, failureThreshold: 3, successThreshold: 1, so liveness is already 30 s of failure before a restart. You are mostly tuning startup and readiness:

probepathperiodtimeoutfailureThresholdbudget
startup/startupz10 s2 s12020 min to load
liveness/healthz10 s1 s330 s of no progress → restart
readiness/readyz5 s2 s210 s to leave endpoints

That 20-minute startup budget is arithmetic, not a guess: a 70B fp16 checkpoint is ~140 GB, and at 1 Gbps line rate 140 GB × 8 = 1120 Gbit ≈ 18.7 min. A default 30 s startup budget would CrashLoopBackOff with exit 137 before the download finished.

Liveness that survives overload. Run the probe server on a separate admin port (:8081) and a separate thread, and have it check a heartbeat rather than the inference queue:

Python
_last_tick = time.monotonic()

def watchdog():                      # ticks every 1 s
    global _last_tick
    while True:
        _last_tick = time.monotonic()
        time.sleep(1)

def healthz():
    return 200 if time.monotonic() - _last_tick < 5 else 503

Trace: watchdog ticks at t=0,1,2,… A saturated inference queue does not stop the ticks, so /healthz stays 200 and the pod is not restarted under load. If the process wedges in a CUDA driver call, ticks stop; at t=5 the handler returns 503, and after 3 failures 30 s later the kubelet restarts it. If the wedge holds the GIL, the handler thread cannot answer at all: the probe fails by timeoutSeconds instead of by 503, which is the same outcome. A Python-thread watchdog cannot see a GIL-holding deadlock any other way; teams that need that use a sidecar process checking a heartbeat file.

Failure modes. (1) Liveness probes a dependency → a registry outage restarts every pod at once; detect it as the RESTARTS column climbing in lockstep across pods while dependency error rate is elevated. (2) Readiness true at socket bind → 5xx or CUDA OOM on the first requests of a rollout; detect as a 5xx spike in the first seconds after a new pod joins. (3) timeoutSeconds below the check's p99 under load → readiness flaps, EndpointSlices churn, in-flight requests get reset; detect as EndpointSlice update rate and client connection resets. (4) Warmup skipped → the first request after ready is 10–50× slower and trips a 5 s client timeout; detect by p99 bucketed by pod age.

Trade-offs. HTTP is cheapest and needs no binary in the image; exec forks a process every period and requires the probe binary to exist; gRPC is the right choice when the server already speaks it. Do not put readiness on the inference port if the inference loop can saturate: a full queue would shed load you could have served. And on reload, prefer keeping the old weights serving until the new ones are warm over dropping readiness, which turns a version bump into a brief outage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Create an end-to-end latency budget for inference.

Answer

Clarify first. I'd ask: what's the SLO and at which percentile, and is it one request class or several? I'll assume a synchronous online service, say a ranking or embedding model behind gRPC, with a 300 ms p99 end-to-end SLO, measured at the caller, and a separate looser budget for batch/offline traffic. p50 is not the contract; the tail is.

The budget. I allocate the 300 ms top-down, at p99, and write it down as a table the team can alert on:

Stagep99 budget (ms)
Network in/out (client↔edge)20
Admission, auth, rate limit5
Queue wait40
Feature retrieval (online store)35
Preprocess / tokenize15
Batch wait20
Execution (GPU forward)90
Postprocess15
Downstream write / async log10
Contingency50
Total300

The contingency is not slack to spend: it's the buffer that absorbs the one stage that misbehaves on a given day.

Why queue wait gets 40 ms and not 5. Queueing is the tail's main driver because wait grows non-linearly with utilization. For a single-server approximation, mean wait Wq = ρS/(1−ρ). With execution service time S = 90 ms, holding Wq at 40 ms means ρ/(1−ρ) = 0.44, so ρ ≈ 0.31: the execution stage has to run near 30% utilization to keep the queue inside budget. At ρ = 0.7 the mean wait is 2.3×S ≈ 210 ms and the budget is gone. p99 wait is worse than the mean, so the real ceiling is lower still. That number is the argument for provisioning headroom rather than running hot.

Batching vs. the deadline. Batching buys throughput and spends latency. The batch wait must be a hard cap (20 ms here), and the deadline must be checked before a request joins a batch:

Python
BATCH_WAIT_P99, EXEC_P99 = 20, 90

def handle(req, deadline_ms):
    remaining = deadline_ms - elapsed_ms()
    if remaining < BATCH_WAIT_P99 + EXEC_P99:
        return reject(DEADLINE_EXCEEDED)  # shed early; don't queue
    return enqueue(req, deadline_ms)

Shedding at admission is cheaper than letting a doomed request occupy a batch slot and a GPU cycle. The deadline propagates as a gRPC deadline header; each hop recomputes remaining time and cancels expired work.

Failure modes and how I'd see them.

  • Queue saturation: p99 queue wait climbs while p50 stays flat. Alert when queue p99 > 40 ms for 5 minutes; the fix is shedding or scaling, not a bigger timeout.
  • Feature-store slowdown: p99 feature fetch > 35 ms. Detect per-dependency spans; fall back to cached or default features and mark the response degraded.
  • Batch-wait inflation: batch wait p99 > 20 ms means the batcher is waiting for a full batch. Watch the batch-size histogram; cap the wait timer.
  • Deadline misses by version: a deadline_exceeded counter labelled by model version and request class. A new model that shifts p99 by 30 ms shows up here before it shows up in the SLO dashboard.

Trade-offs. Static per-stage budgets are simple and alertable but waste headroom when one stage is fast. Deadline-aware admission is adaptive but harder to reason about and can starve low-priority classes. The choice flips when traffic is throughput-bound rather than latency-bound: for offline batch scoring, optimize average throughput and drop the per-request deadline entirely.

Decision point. If I had to pick one lever: hold execution utilization near 30% and shed at admission, because the queue, not the model, is what blows a 300 ms p99.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Tune dynamic batching for a latency-sensitive GPU model.

Answer

Assumptions: Triton Inference Server, one L4-class GPU, a single-pass transformer encoder, p99 SLO of 50 ms, peak 200 QPS, sequence lengths 32–512.

The answer. Set max_batch_size to the largest batch that fits in GPU memory at your longest sequence. Find the knee of the throughput-vs-batch-size curve and put those sizes in preferred_batch_size. Then raise max_queue_delay_microseconds from its default of 0 in small steps (1, 2, 5 ms) until p99 sits just under the SLO at peak QPS. That delay is your latency budget for batching; spend it, don't exceed it. Instance count and client concurrency are tuned after, not before.

Why it works. Per-request GPU work has a fixed component: kernel launches and reading model weights from HBM. For a memory-bandwidth-bound layer, the weights are read once per batch no matter how many requests are in it, so a batch of 8 reads the same bytes as a batch of 1 and does eight times the useful work. Throughput per request climbs with batch size until the kernel turns compute-bound, which is where the curve flattens: that's the knee you want preferred_batch_size to sit on. Queue delay is what you pay for it. It is added to every request in the batch, and the request that arrives last waits the full delay, so p99 ≈ compute(batch) + queue_delay + arrival variance. The tail moves faster than the median because the delay is a step function: a request landing just after a batch forms waits a whole cycle.

Worked numbers (hypothetical, single L4, 200 QPS):

configp50p99throughput
no batching, 1 instance12 ms15 ms40 QPS
max_batch 8, delay 014 ms22 ms95 QPS
max_batch 8, delay 5 ms18 ms41 ms180 QPS
max_batch 8, delay 10 ms24 ms68 ms195 QPS

The last row buys 8% throughput for a p99 that misses the 50 ms SLO: stop at 5 ms.

Failure modes and how you see them.

  • Delay with no fill: at off-peak QPS the batch never reaches 8, so you pay latency for nothing. Watch the batch-size histogram; if the median batch is 1–2, drop the delay.
  • Tail blowout: p99 minus p50 widening. Triton exports nv_inference_queue_duration_us; alert on its p99, not its mean.
  • OOM: max_batch_size too large for long sequences. Watch nv_gpu_memory_used_bytes and OOM lines in the server log.
  • Head-of-line blocking: one 512-token request in a batch stalls the 32-token ones. Plot per-request latency against sequence length; if it correlates, split long and short into separate models or instance groups.
  • Deadline storms: client timeout shorter than queue delay plus compute. Track the client-side deadline-exceeded rate.

When not to batch. If the SLO is p99 under ~10 ms at low QPS, batching cannot pay for itself: add instances instead. And for autoregressive decode, Triton's dynamic batcher is the wrong tool: use continuous (in-flight) batching in TensorRT-LLM or vLLM, where batches re-form every decode step and queue delay is near zero.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design autoscaling for a slow-loading accelerator model.

Answer

Clarify the SLO and the model's cold-start profile first. Assume a 7B-parameter model on an A100: loading weights from disk to GPU memory takes ~120 s, CUDA context init and first inference add ~30 s. Target p99 latency < 500 ms for interactive traffic. Each replica handles 5 concurrent requests at that latency (from a capacity test).

Use a two-tier autoscaler. Tier 1: a warm pool of replicas kept ready. Size it to absorb the largest burst you can't wait 150 s for. Tier 2: a leading autoscaler that scales on queue depth per replica, not CPU. In Kubernetes, use KEDA with a Prometheus trigger on a queue-depth metric (e.g., number of pending requests in a Redis list or SQS queue). Set target queue depth per replica to 10 (from capacity test: at 10 queued, p99 stays under 500 ms). Scale-up stabilization window 0 s; scale-down 600 s. Cap max replicas by GPU quota (e.g., 20 A100s). Pre-scale for known peaks with a cron trigger (e.g., 9 AM weekdays).

Queue depth leads latency: it grows as soon as arrival rate exceeds service rate, before p99 breaches. CPU misleads because GPU inference is GPU-bound; CPU may sit at 20% while the GPU is saturated, and CPU spikes during data loading, not compute. Warmup dominates because a new replica cannot serve for 150 s; scaling on CPU would react after the queue is already deep.

Warm pool costs idle GPU time. Skip it when the SLO tolerates cold starts (e.g., batch jobs with 5-minute deadlines) or when load time < 10 s. Alternative: serverless GPU (e.g., Modal, Replicate) hides cold starts but costs more per request and limits control. Deciding criterion: if p99 SLO < 1 s and load time > 30 s, warm pool is mandatory; otherwise, cold-start with queueing is cheaper.

Failure modes:

  1. Scale-out too slow: queue depth grows, p99 exceeds SLO. Detection: alert if queue depth > 2x target for 60 s. Cost: dropped requests (HTTP 429 from admission control) or SLA breach.
  2. Scale-down too aggressive: replicas terminated mid-request. Detection: readiness probe failures during termination; use preStop hook to drain for 30 s.
  3. Warmup failure: model OOMs or fails to load. Detection: readiness probe fails for > 5 min; alert.
  4. GPU quota exhausted: autoscaler hits maxReplicas, queue grows. Detection: maxReplicas reached metric; mitigate with admission control.
SignalLeads demand?Misleads whenTarget example
CPUNoGPU-bound inference70%
Queue depthYesQueue empty but burst imminent10 per replica
ConcurrencyYesLong-running requests skew5 per replica

Worked example (hypothetical): Traffic peaks at 50 req/s. Each replica serves 5 req/s at p99 500 ms. Need 10 replicas. Warm pool = 5. A burst adds 5 req/s. Queue depth grows at 5 req/s. Scale-out adds 5 replicas in 150 s. During that time, 750 requests queue. With admission control at 1000, no drops. If burst is 20 req/s, queue hits 3000 in 150 s; admission control drops 2000. So pre-scale for predictable bursts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a production real-time inference service.

Answer

Assumptions I'd state before designing anything: synchronous request/response, one model per endpoint, GPU-backed, p99 end-to-end SLO of 150 ms at 200 rps peak with 3x burst headroom, and a hard requirement that a stale or degraded prediction beats a 500. If any of those are wrong (batch is fine, or the client can poll) the design changes, so I'd confirm them first.

The core answer: split the latency budget, then make each stage fit its slice.

stagep50p99 budget
edge + TLS + routing2 ms8 ms
admission + queue wait1 ms30 ms
feature fetch (one Redis round trip)3 ms15 ms
preprocess / tokenize2 ms6 ms
model forward (batch 1, A10G)18 ms45 ms
postprocess + serialize1 ms6 ms
total27 ms110 ms

That leaves ~40 ms of slack for retries and jitter. When a stage can't fit its slice, that's the design conversation, not "add more GPUs."

Serving runtime. Triton with dynamic batching: max_batch_size: 32, max_queue_delay_microseconds: 5000. The 5 ms queue window is the knob that matters: it trades p50 latency for throughput, and the curve is steep up to batch ~16 before it flattens, because a GPU forward pass is dominated by fixed kernel-launch and memory overhead at batch 1. For an LLM, use vLLM with continuous batching instead: decode is memory-bandwidth-bound, and static batching wastes the KV cache while one sequence finishes.

Admission control: reject early, not late. A token-bucket limiter per tenant plus a global concurrency cap sized to GPU_count × max_concurrent_sequences. Once the queue exceeds the 30 ms wait budget, shed to the fallback rather than queue: a 400 ms answer is worse than a cached one.

Python
deadline = time.monotonic() + 0.150
if not limiter.acquire(tenant, timeout=0.005):
    return fallback(tenant)        # cached / smaller model / heuristic
resp = await infer(req, deadline=deadline)
if resp is None:                   # deadline exceeded inside the runtime
    return fallback(tenant)

Failure modes, and how each is detected.

  • Queue saturation. p99 climbs well before error rate does. Alert on queue-wait p99 > 30 ms, not on 5xx: by the time 5xx fires you've already blown the SLO.
  • Retry storm. Retries multiply load exactly when the service is weakest. Budget them at 10% of requests, idempotent reads only, 20 ms cap, full jitter. One hedged request after p95 beats N sequential retries.
  • Cold start. A new GPU pod takes 25–40 s to load weights and warm CUDA kernels. Keep 1–2 warm pods, and don't let readiness pass until a synthetic request completes end to end.
  • Silent quality drift. Latency SLOs won't catch a model that got worse. Log input hashes and output distributions; alert on PSI > 0.2 on key features.

Alternatives, and when not to use them. Dynamic batching wins when requests are independent and the model is GPU-bound; it loses for long-lived streams (continuous batching) and when p99 < 20 ms is required (batch 1, more replicas). Synchronous serving wins when the client needs the answer now; if the client can poll, an async queue with a callback absorbs bursts without over-provisioning for peak.

Rollout. Canary 1% for 30 minutes, compare p99 and output-distribution metrics against the incumbent, then 10/50/100. Rollback is a routing change, not a redeploy: keep the previous model version resident.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design observability for an inference endpoint.

Answer

Clarify and assume. I'd ask: is this a synchronous request/response endpoint (classifier or LLM), what's the p99 latency SLO, and do we get ground-truth labels later? Assume a GPU-backed HTTP endpoint, p99 target 300 ms, labels arriving within 24h, and a versioned model artifact.

Core answer. Observability here is four layers, and the ordering matters because each catches a different failure.

  1. Request-level RED: rate, errors, duration, split by model version and request class. This is the layer that pages.
  2. Stage-level tracing: admission → queue → batch formation → preprocess → accelerator execution → postprocess → response. One span per stage via OpenTelemetry, with the model artifact hash as a span attribute.
  3. Model and data quality: input validation, feature freshness, prediction distribution, slice metrics, and delayed ground truth joined back to the prediction log.
  4. Cost and saturation: accelerator utilization, memory, batch occupancy, tokens or FLOPs per request, and $/1k requests by version.

Mechanism: why queue time is the signal. Execution time on a GPU is roughly flat until the accelerator saturates; queue time absorbs the overflow. With dynamic batching, a request arriving just after a batch closes waits for the next window. So when traffic rises, p99 queue time climbs first, then execution time follows once the batch is full. If you only alert on total latency you page late. Alert on queue time p99 and batch occupancy separately.

Mechanism: why delayed ground truth matters. Without labels you can only see distribution shift, not correctness. A shift in prediction distribution could be a real traffic change or a broken feature pipeline. Joining labels back to the prediction record (keyed by request ID, storing model version and feature hash) is what separates "the model got worse" from "the inputs changed." That join is the expensive part: you must retain the prediction record long enough to cover label latency.

Trade-off: payload logging. Full request/response payloads make debugging trivial but cost storage and carry PII. Three options: (a) log everything, redact at the SDK; (b) sample 1% with a stable hash on request ID; (c) log only feature hashes, embedding sketches, and distribution summaries. I'd pick (b) plus (c) for the aggregate view. The deciding criterion is whether you have a data-quality incident more than once a quarter, if so, raise the sample rate; if you're under GDPR/HIPAA, redact before the log leaves the process.

Failure modes and detection.

FailureDetection signalCost if missed
Silent model regressionPSI on prediction distribution > 0.2 plus delayed accuracy dropHours of wrong answers
Queue saturationqueue p99 > 50 ms while execution p99 flatTimeouts, retries amplify load
Telemetry gapmissing series / cardinality drop for a versionBlind during incident
Feature stalenessfeature timestamp age > 2× refresh intervalPredictions on stale inputs

(Figures are illustrative.)

Artefact: a request trace. Hypothetical, 300 ms budget:

admission      2 ms
queue         18 ms   <- alert threshold here
batch form     1 ms
preprocess     9 ms
gpu exec     210 ms
postprocess    6 ms
response       4 ms
total        250 ms

If queue jumps to 120 ms, total is 352 ms and you breach p99. That's the page.

Runbooks. Queue saturation → reduce max batch size or shed low-priority classes. Model regression → roll back artifact version. Telemetry gap → fail open to the previous known-good dashboard, not to silence.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Load-test an inference service before launch.

Answer

Start by pinning the SLO and the workload. I'd ask: which model, which GPU, which serving stack, what traffic mix, and what latency/error/quality targets? Assume a 7B FP16 model on one A100 80GB, vLLM, p99 TTFT < 800 ms, TPOT < 50 ms, error < 0.1%, and a 30-day launch. If those differ, the numbers move.

Derive the workload from production: prompt tokens, output tokens, arrival process, tenant mix, cache hit rate. Replay a production trace if you have one; otherwise synthesize p50/p95/p99 lengths and a Poisson arrival, then add a burst. Use k6 or Locust for HTTP, Prometheus for metrics, and the engine's own queue/KV-cache metrics. In vLLM, --gpu-memory-utilization defaults to 0.90; I'd set it to 0.85–0.90 to leave fragmentation room.

Run phases: warm steady state, ramp, burst, soak, cold start, model reload, cache miss, dependency slowdown, node loss, quota exhaustion, malformed requests, cancellation, recovery. For each, define the signal that fails.

phasepass signalfail signal
warm steadyp99 TTFT/TPOT within SLO for 30 mindrift or OOM
rampthroughput scales with replicasqueue grows, p99 TTFT > SLO
burstqueue drains in < 2× burst durationqueue never drains
soakmemory flat over 24 hKV-cache leak
cold startfirst token < 2× warm TTFTtimeout
model reloadnew model serves within 120 s5xx during reload
cache missp99 TTFT < 2× warmcache-miss storm
dependency slowdownerror budget holdsTTFT p99 crosses SLO
node losscapacity drops, no data lossstuck requests
quota exhaustion429s, no retry stormcascading 5xx
malformed400s, GPU idleGPU work on bad input
cancellationKV freedKV held
recoverydrain time < 2× burstqueue backlog

Mechanism: continuous batching joins requests at each decode step. Throughput rises with batch until KV cache or compute saturates. TTFT = queue wait + prefill; TPOT = decode step time. Autoscaler lag: HPA reacts in tens of seconds; model load adds 30–120 s. So a burst can queue before capacity arrives. Saturation is not capacity because the max-throughput batch often violates p99 TTFT.

Worked example (hypothetical): 7B FP16, 32 layers, 32 heads, head_dim 128. KV cache per token = 2 × 32 × 32 × 128 × 2 bytes = 0.5 MiB. With 60 GB for KV, that's ~120k tokens, or ~60 concurrent 2k-token sequences. At batch 32, TPOT 40 ms → 25 tokens/s per stream, 800 tokens/s aggregate. At batch 64, TPOT 60 ms → 16.7 tokens/s per stream, 1067 tokens/s aggregate, but p99 TPOT misses 50 ms. Sustainable batch is 32, not 64.

Failure modes: dependency slowdown. Retrieval p99 goes 50 ms to 500 ms, queue depth grows, TTFT p99 crosses SLO; detect with per-stage spans. Node loss: GPU node drains, in-flight requests fail; error rate spikes and capacity drops; detect via pod restarts and error rate. Quota exhaustion: provider returns 429s; detect via 429 rate. Malformed requests: 400s, no GPU work; exclude from throughput. Cancellation: client disconnects; vLLM should abort the sequence and free KV blocks; detect if KV-cache usage does not drop. Recovery: after burst, measure queue drain time.

Trade-offs: replay vs synthetic. Replay captures cache hit rate and tenant mix; synthetic stresses a dimension. Use both. Autoscale on queue depth vs GPU utilization: queue depth reacts earlier but can thrash; GPU utilization lags. Leave 30% headroom over sustainable throughput. Run at 60–70% of the batch that meets p99. That is production capacity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Investigate rising p99 latency with unchanged mean execution time.

Answer

What I'd say in the first two minutes

Mean flat with p99 rising means the distribution changed shape, not its center. Two shapes do this: a new slow subpopulation (bimodal. One cohort of requests now takes 10x longer) or the same population pushed into a queue (service time unchanged, wait time growing). The mean is structurally blind to both, so I stop reading it and go to the histogram.

Why the mean hides it: 10,000 requests. Baseline is 9,900 at 40 ms and 100 at 60 ms: mean 40.2 ms, p99 60 ms. After a deploy, 9,900 at 36.6 ms and 100 at 400 ms: mean still 40.2 ms, p99 400 ms. A 3.4 ms win in the bulk exactly pays for a 340 ms loss in the tail. Every dashboard keyed on mean stays green.

Mechanism

Queueing, M/M/1 with 50 ms service time: at ρ=0.75 the mean wait is ρ/(1−ρ)·S = 150 ms; at ρ=0.9 it is 450 ms. Service time never moved. Real services with c servers and lower variance sit below these numbers, but the shape, wait growing as 1/(1−ρ), is why a 20% traffic bump can triple p99.

Bimodal: a new code path, a cold cache, a larger payload cohort, or a GC pause hits a subset. You find it by segmenting, not by staring at the aggregate.

What I'd actually run

Pull the histogram, not the summary: histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m]))). Check the bucket layout first: with buckets at 50/100/250/500 ms the p99 is linearly interpolated inside a bucket and can be off by tens of ms. Native histograms or HdrHistogram avoid that.

Then split the latency into admission → queue → batch wait → preprocess → execution → postprocess → network. If execution p99 is flat and queue p99 moved, it is capacity or scheduling, not code. Continuous profiling (async-profiler, Pyroscope) for GC and lock contention; bpftrace off-CPU time for queue wait.

SegmentWhat a p99 shift there implicates
version / deploy timenew code path, regression
pod agecold start, JIT warmup, cache fill
payload / token countbimodal cohort, head-of-line blocking
tenant / routenoisy neighbor, per-tenant quota
region / hardwarecapacity, instance type skew
cache statemiss storm

Failure modes and how I'd catch each

  • GC pauses: p99 spikes at regular intervals, correlated with heap growth. Check jvm_gc_pause_seconds or a wall-clock profile.
  • Cold starts and autoscaler lag: p99 grouped by pod age; new pods slow for the first ~30 s.
  • Retries: a 1% timeout with 3 retries adds 3% load and can double p99. Check the retry counter and duplicate request IDs.
  • Head-of-line blocking in a shared pool or batch: batch wait grows with batch size. Plot wait time against batch size.
  • Dependency tail: downstream p99 propagates. Check span-level p99 per dependency.

Trade-offs

  • Head sampling at 1% misses the tail entirely; tail-based sampling in the OTel collector keeps slow and error traces but buffers spans in memory, so cost scales with traffic.
  • You cannot average p99 across instances: merge histograms. Finer buckets buy accuracy and cost cardinality and memory.
  • Segmenting by tenant, route and payload is how you find the cohort, but each label multiplies series. Cap metric cardinality and keep the high-cardinality split in traces.

Reproduce and verify

Replay the affected payload cohort or drive the concurrency to the level where p99 moved, change one constraint, and count deadline misses, requests over SLO, not the mean.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Prevent overload and retry storms in an inference API.

Answer

What I'd say first. Assume a fixed GPU fleet: 4 replicas, each serving one request at a time, 50 ms mean service time, so 80 req/s of capacity, and clients that retry on timeout or 5xx. The goal is to hold p99 under 200 ms and stop retries from multiplying load. Two independent controls do most of the work: an admission limit that bounds in-flight work, and a retry budget that bounds retry traffic as a fraction of successful traffic. Deadline propagation and jittered backoff are the supporting pieces.

Admission control. Cap in-flight requests with a semaphore. Size it from Little's Law: at saturation λ = 80 req/s, in-flight L = λW, so W ≤ 200 ms means L ≤ 16. Set max_inflight = 16: 4 in service, 12 queued. Anything past that gets 429 immediately instead of joining an unbounded queue. The semaphore wait is bounded by the request's remaining deadline, so a request that would expire while queued is shed rather than consuming a slot.

Retry budget. Retries get their own token bucket, refilled by successes rather than by time. Each successful non-retry request adds 0.1 tokens; each retry costs 1. Cap the bucket at 80 tokens (10 s of burst). At 80 req/s of success the budget refills at 8 tokens/s, so retries can never add more than 10% to steady load.

Python
import time, threading

class Gate:
    def __init__(self, max_inflight, retry_cap, retry_fraction=0.1):
        self.sem = threading.BoundedSemaphore(max_inflight)
        self.retry_cap = retry_cap
        self.retry_fraction = retry_fraction
        self.tokens = retry_cap
        self.lock = threading.Lock()

    def on_success(self):
        with self.lock:
            self.tokens = min(self.retry_cap, self.tokens + self.retry_fraction)

    def allow_retry(self):
        with self.lock:
            if self.tokens >= 1:
                self.tokens -= 1
                return True
            return False

    def handle(self, req):          # req.deadline is a time.monotonic() timestamp
        if req.is_retry and not self.allow_retry():
            return 429, "retry budget exhausted"
        remaining = req.deadline - time.monotonic()
        if remaining <= 0 or not self.sem.acquire(timeout=remaining):
            return 429, "shed"
        try:
            resp = serve(req)       # the model call
            if not req.is_retry:
                self.on_success()
            return resp
        finally:
            self.sem.release()

Trace. Steady state: 80 successes/s → 8 tokens/s, bucket sits near its 80-token cap. A downstream blip makes 500 clients retry at once. allow_retry() drains the 80 tokens for the first 80 retries; the remaining 420 get 429 without touching the GPU. The bucket then refills at 8/s from ongoing successes. The storm lands as 80 immediate retries plus 8/s, at most 10% of capacity, instead of 500 requests, which is 6.25× the fleet's steady load. The retry token is spent before the semaphore, so a retry later shed by admission still counts against the budget; that's deliberately conservative.

ControlBoundsTune onFailure if missing
Concurrency semaphorein-flight work → GPU queue, memoryp99 vs. throughputqueue grows unbounded, latency cliff, OOM
Deadline propagationwork on already-expired requestsclient timeout distributionGPU serves requests nobody is waiting for
Retry budgetretry load as % of successretry rate, error rateretry storm multiplies load
Full-jitter backoffretry arrival synchronizationretry latency budgetsynchronized retry spikes
Per-tenant limitsblast radius of one noisy tenantper-tenant SLOone tenant starves the rest

Alternatives and when not to use this. Queue vs. shed is the main dial: a tight 200 ms SLO means shed early; batch or offline inference that tolerates seconds can queue deeper and shed later. A circuit breaker is usually wrong on the model server itself: it's the only dependency, so tripping it leaves nothing to serve; put breakers on downstream dependencies (feature store, tokenizer service) instead. Autoscaling should key on queue depth, but a new GPU replica takes 2–5 minutes to become ready, so shedding has to cover that window. Inference is read-only, so retries are safe; if the endpoint has side effects (billing, audit log), require idempotency keys.

Failure modes and detection. No concurrency cap: in-flight grows, queue depth climbs, p99 goes from 200 ms to seconds. Watch the in-flight gauge pinned at the limit and queue age rising. No retry budget: a 500-client storm becomes 1500 requests against an 80 req/s fleet. Alert when retries exceed 20% of total requests. No jitter: retries arrive in synchronized waves. The retry arrival histogram spikes at multiples of the backoff base. No deadline propagation: the GPU stays busy on expired requests. Track the fraction of served requests whose deadline had already passed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Handle malformed and adversarial inference inputs.

Answer

Core answer (first 90 seconds). Assume a multi-tenant HTTP/gRPC inference service, JSON or binary tensor bodies, tenants you don't trust. Validate in four gates, all of them before the request reaches a GPU: transport, decode, schema, execution. Reject with a machine-readable reason code; never coerce. The contract is "we accept exactly this shape of input", not "we accept anything and try to make it work".

  • Transport: authenticate, rate-limit per tenant, require Content-Type: application/json or application/octet-stream, cap the body at 1 MB.
  • Decode: decompress with a hard output cap, not just an input cap. DEFLATE's theoretical maximum ratio is 1032:1 (RFC 1951), so a 1 MB body can expand to roughly 1 GB. Cap output at 10 MB and ratio at 100:1, and run it in a subprocess with an RSS limit.
  • Schema: strict types, exact field set, ranges; for tensors, len(body) == prod(shape) * itemsize with an allowlisted dtype and positive dims.
  • Execution: a deadline, a batch cap, and a token cap measured after tokenization.

Why this order. GPU work is the expensive step, so everything cheap and rejecting happens first. Two JSON details bite in practice. Python's json.loads accepts the bare literals NaN, Infinity and -Infinity by default, non-standard JSON that most other parsers reject, so pass parse_constant to raise instead. And CPython's C scanner raises RecursionError on deeply nested arrays, so cap nesting depth (32 is generous) rather than letting a 100k-deep array reach the parser. Duplicate keys silently keep the last value; reject them if the field is security-relevant.

Validator, Python 3.11 / Pydantic 2.7:

Python
import math
from typing import Annotated
from pydantic import BaseModel, Field, field_validator

Features = Annotated[list[float], Field(min_length=1, max_length=1000)]

class InferenceRequest(BaseModel):
    features: Features

    @field_validator("features", mode="before")
    @classmethod
    def reject_non_finite(cls, v):
        if not isinstance(v, list):
            raise ValueError("features must be a list")
        for x in v:
            if isinstance(x, bool) or not isinstance(x, (int, float)):
                raise ValueError("features must be numbers")
            if not math.isfinite(x):
                raise ValueError("NaN/Inf not allowed")
        return v

Trace. {"features": ["a"]} reaches the validator with v == ["a"]. The isinstance check fails on "a" and raises ValueError, which Pydantic converts to a ValidationError → HTTP 422 with a reason code. Drop that isinstance line and math.isfinite("a") raises TypeError instead; Pydantic only converts ValueError and AssertionError, so the TypeError escapes as an unhandled 500. That is the adversarial case: the attacker's goal is the unhandled path, not the rejected one. mode="before" matters because it sees the raw parsed JSON, so it also catches a NaN literal that json.loads produced.

GateLimitRationale
Edge1 MB body, 100 req/min/tenantBounds work before parsing
Decoderatio ≤ 100:1, output ≤ 10 MBDEFLATE max is 1032:1
JSONdepth ≤ 32, no NaN/Inf, no dup keysCPython scanner recursion
Schemaexact fields, 1 ≤ len ≤ 1000Blocks type confusion
Tensorlen == prod(shape)*itemsize, ≤ 10^7 elementsBlocks shape/dtype confusion
Execution5 s deadline, batch ≤ 32Bounds GPU occupancy

Trade-offs. Strict validation costs roughly 1–5 ms per request and rejects legitimate edge cases: sparse tensors, Unicode normalization variants, integers where floats are expected. For trusted internal callers, sanitize rather than reject. The criterion is whether a bad input costs more than a false rejection, if it does, reject.

Failure modes. Decompression bomb: RSS alert plus OOMKill count, and the fix is the output cap, not a bigger node. Tokenizer blowup: a 1 KB string of combining marks can tokenize to thousands of tokens, so cap tokens after tokenization, not characters before. Slow generation: a valid request with a huge max_tokens holds a slot; detect via queue depth and deadline-exceeded counters. Silent NaN coercion: the model returns a confident wrong answer, detected only by input-distribution monitoring, which is why you reject instead.

Testing. Fuzz with Hypothesis over oversized, nested, NaN, sparse, Unicode and truncated-gzip corpora, and assert that every rejection is a 4xx with a reason code: never a 5xx.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Operate a multi-model shared serving cluster.

Answer

Core answer (first ~90 seconds)

Assume one cluster, say 8× H100 80 GB nodes, a dozen models from 1B to 70B, mixed tenants, one shared ingress. The scarce resource is not GPU count: it's HBM bytes and the KV cache that lives in them. So I'd answer in three moves: size each model's real footprint, cap concurrency per model so it can't exceed its share, and give anything with a hard SLO its own slice.

Sizing: weights are the easy part. Llama-70B in bf16 is ~140 GB, so it doesn't fit on one 80 GB H100 and needs tensor parallelism ≥ 2. The part people miss is KV cache. Per token for that model: 80 layers × 8 KV heads × 128 head dim × 2 (K and V) × 2 bytes = ~320 KB/token. A 4k-token sequence costs ~1.3 GB of KV; 100 concurrent 4k sequences is ~131 GB: more than a whole H100. That's why "reserve headroom" is a number, not a slogan: vLLM's gpu_memory_utilization defaults to 0.9, meaning it claims 90% of free HBM at startup for weights plus the KV pool. Two models on one GPU both left at 0.9 will OOM on the second load. Set it explicitly per model and leave the remainder for activations and the CUDA context (~1–2 GB).

Admission: bound in-flight requests per model with a queue-depth cap and reject past it with 429/503 rather than letting the queue grow. vLLM preempts requests when the KV pool is exhausted, by recompute or swap, so an unbounded model will silently steal another's cache. Priority classes plus preemption let a latency-critical model reclaim; the batch model gets preempted instead.

Isolation options:

optionisolationcost
MPS / time-slicememory shared, no fault isolationbest utilization; one crash can take the GPU
MIG (1g.10gb etc.)hard memory + faultcan't share spare memory across slices
dedicated node/poolfulllowest utilization

Failure modes and how you see them:

  • CUDA OOM at load: a second model's utilization collides with the first. Detect: load-failure counter, OOMKilled, "CUDA out of memory" in logs.
  • Preemption storm: KV thrash between models. Detect: per-model preemption/recompute rate, TTFT p99 diverging between models.
  • Cold-load stampede: the autoscaler brings up five replicas, all pulling 140 GB from the same NFS at ~1–2 GB/s, loads take minutes and readiness never flips. Detect: model-load-duration histogram, node NIC/disk saturation.

When dedicated wins: if a model's footprint is already >50% of a GPU and its SLO is p99 TTFT < 500 ms, sharing buys little and costs you the noisy-neighbor risk. Give it the slice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

In a shared serving cluster, how do you route a request to a specific pinned model version, and how do you verify the version that actually served it is the one you intended?

Answer

Pin at the request, not at the deployment. Three things have to line up: the selector travels with the request, the router only considers replicas that have that version loaded, and the response carries back the version that actually ran so you can compare it against what you asked for.

Carrying the selector. In Triton the model repository is models/<name>/<version>/model.plan, and the version policy decides what is loaded: latest (the default) loads one version, all loads every version directory. The request names the version:

{"model_name": "ranker", "model_version": "7", "inputs": [...]}

An empty model_version means latest, which is exactly the silent-fallback trap: any proxy that drops the field turns a pinned request into a latest request. A version that isn't loaded returns an error rather than substituting another version: that is the property you want, and it is why you never let the field default.

On KServe the pin is the revision: predictor pods carry the revision label, and a pinned client targets the revision host rather than the top-level InferenceService host, because canaryTrafficPercent splits at the router and will happily send a pinned request to the canary. On SageMaker, versions are production variants in an endpoint config (ModelName plus InitialVariantWeight); InvokeEndpoint(..., TargetVariant="v2") pins, and the response header x-amzn-Invoked-Production-Variant names the variant that served.

Replica eligibility. A pod being Ready is not the same as a pod having v7 loaded. Model load takes seconds to minutes, so during a rollout the router's endpoint list must be keyed on loaded version, not on pod readiness. Triton's dynamic batcher runs per model instance, and each version is its own instance, so a batch never mixes versions: you don't have to defend against that, but you do have to defend against routing to an instance that has the wrong one.

Verification, three layers.

layermechanismattestation
requestmodel_version in body; TargetVariant; revision hostresponse model_version; x-amzn-Invoked-Production-Variant
replicarouter selects only replicas with the version loadedper-version readiness; load log with digest
fleetone version per revision/variant, digest in the identityper-version metrics; digest in model metadata

Per request: log requested version, served version and request id; a version_mismatch counter that must stay at zero. Aggregate: Triton exposes nv_inference_count and nv_inference_request_success labelled by model and version, so sum by (version) (rate(nv_inference_count{model="ranker"}[5m])) should show the pinned version carrying all the traffic and every other version at zero. A version you didn't intend with nonzero counts, or the pinned version at zero while clients are calling, is the alert. Artifact: record the digest of the weights at load and expose it in the model metadata response. A version label without a digest is a name, not an identity: two different files under version=7 on two replicas is the failure pinning is supposed to prevent.

Failure modes. Dropped selector → server defaults to latest; detect with the mismatch counter. Router keyed on pod readiness → 404s or wrong-version answers during rollout; detect with error rate split by version. Canary split intercepting pinned traffic → per-version counts deviate from the expected split. Same label, different weights → digest mismatch at load; refuse to serve rather than answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Roll back a model-serving release safely.

Answer

Assumptions I'd state first: the model sits behind an HTTP API on Kubernetes, artifacts (weights, tokenizer, preprocessing code) are pushed to an OCI registry by digest, and the release is a canary with weighted routing. If the model is loaded from a mutable S3 path instead, rollback isn't a routing change: it's a rebuild, and that changes the answer.

Core answer. A safe rollback restores the previous consistent tuple: weights digest, tokenizer/preprocessing, runtime image, serving config, and capacity: shifts traffic back to it, then proves the restored version is the one you think it is. The common mistake is treating rollback as "redeploy the old image." Weights and tokenizer are versioned separately; a tokenizer that doesn't match the weights doesn't crash, it silently produces worse output: the same failure you were rolling back from.

Mechanism. Keep the previous tuple deployable, not just archived. Content-address every artifact by sha256 so "previous" is a digest, not a tag; keep the previous runtime image pulled on the nodes; keep at least 2 warm replicas of the old version during the canary. Warm replicas are what make rollback a routing flip (sub-second) instead of a cold start: a 7B fp16 model is ~14 GB and takes 30–60 s to load on an A10G, and a 70B sharded across 4 GPUs takes minutes. During those minutes you have zero serving capacity, which is worse than the bug.

Triggers and authority. Two classes, because they fire on different clocks. Technical: 5xx above 1% for 5 min, or p99 above 2x baseline (180 ms → 900 ms). Model-quality: eval score drop, refusal rate, or thumbs-down rate. These lag by hours because they need labeled or user feedback, so they can't be the only trigger. Name one person with authority to flip the weight; a committee doesn't roll back at 3 a.m.

In-flight work. Streaming responses (token-by-token LLM output) can't be cut instantly. Drain: stop routing new requests to the new version, let open streams finish within a bounded window (30 s), then hard-cut the remainder. Draining means both versions serve simultaneously for that window: downstream consumers must tolerate mixed outputs, or you hard-cut and accept truncated responses. Retries during the flip need idempotency keys, or a client retry double-writes.

Verify, then hold. After the flip, check the server's /metadata reports the expected weights digest and tokenizer hash, replay a golden set (200–500 prompts) against the known-good baseline, and confirm p99, error rate, and fallback rate are back. Then set a hold flag on the deploy pipeline, if auto-promotion runs on green health checks, the next pipeline run re-promotes the broken version and undoes your rollback.

Rollback vs roll-forward. Roll back when the previous version is known-good and the new one is broken. Roll forward when the new release changed the output schema or API contract, then the old version no longer satisfies consumers, and "rollback" breaks them differently. The deciding question is whether the previous tuple is still a valid contract.

Failure modes. Rollback that restores weights but not the tokenizer → silent quality regression, caught only by the golden set. Rollback with no warm replicas → cold-start outage, seen as a capacity cliff in the trace. Auto re-promotion → the rollback silently reverts, seen as the digest changing back with no deploy event.

t=0:00  canary at 5%; 5xx = 3.2% vs 0.2% baseline over 5 min -> auto trigger
t=0:00  flip routing to 0% new / 100% old; old replicas already warm -> no cold start
t=0:00  stop new-version intake; 340 open streams drain, 30 s window, then hard-cut
t=0:30  /metadata digest == known-good sha256; tokenizer hash matches
t=1:00  golden set (300 prompts) replayed vs baseline; p99 900 ms -> 180 ms
t=5:00  hold flag set on deploy pipeline; no auto re-promote

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How do you evolve the input/output contract of a served model: tokenizer version, prompt template, preprocessing steps, tensor shapes, embedding dimension, output format: without breaking existing clients?

Answer

The HTTP schema is not the contract. For a served model the contract is the tuple that turns bytes into a prediction: tokenizer artifact and revision, prompt template, preprocessing config, input tensor name/dtype/shape, output tensor name/dtype/shape, and decoding or postprocessing parameters. Two of those can change while the request body stays byte-identical, and the client gets a different answer. So I version the tuple, not the endpoint.

Every deployable is an immutable bundle (weights, tokenizer files, template, preprocessing code) content-hashed, and that hash is the contract version. Triton's model repository already has this shape: each version is a numbered directory, and config.pbtxt declares the tensor spec.

protobuf name: "embed" platform: "python" input [{ name: "text" data_type: TYPE_STRING dims: [ -1 ] }] output [{ name: "embedding" data_type: TYPE_FP16 dims: [ 768 ] }] version_policy { specific { versions: [ 1, 2 ] } }

version_policy keeps both versions resident; the request carries the contract version (header or field) and the response echoes it plus the artifact hash. No client ever resolves "latest". Triton does not check a client-declared contract, so the routing layer owns that.

Then I classify the change before shipping it:

changesame request body?client impacthandling
new optional field, new output keyyesnone if unknown keys ignoredadditive, ship behind default-off
tokenizer bump, template edit, normalization changeyessilent semantic driftnew contract version, shadow eval, explicit opt-in
embedding dim 768→1024, dtype fp16→fp32, output formatyesdownstream index or parser breaksnew version, dual-serve, hard sunset

Detection is the part teams skip. A latency-only canary passes a tokenizer bump with p99 flat and outputs quietly different. I keep a golden prompt set per contract version with expected outputs, watch output-distribution drift, and assert embedding dimension client-side. Triton metrics are labeled by model and version (nv_inference_request_success, nv_inference_request_duration_us), so old-version traffic decay is visible and a client that never migrated shows up as a flat line rather than a surprise at removal.

Dual-serving has a real bill. A 7B fp16 model is ~14 GB of weights; two versions is ~28 GB, which fits a 40 GB A100 but not a 24 GB card. When memory does not allow it, route the old version to a small dedicated pool and accept the extra instance rather than co-locating.

Deprecation: publish the contract version, a sunset date, and per-client usage telemetry; remove the old version only after zero traffic across a full business cycle. The failure mode to name out loud is a shape-compatible change shipped as a patch: it is the one that breaks nobody's parser and everybody's meaning.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Serve a stateful sequence model correctly.

Answer

Assumptions. "Stateful sequence model" here means an autoregressive decoder whose per-session state (the KV cache) must survive across turns of a conversation or stream. Clients send a session id; turns within a session must be applied in order. Replicas are GPU workers behind a load balancer, and the cache lives in GPU memory where it is not cheap to move.

Core answer. Pin each session to one replica for its lifetime and route by consistent hash on the session id, so the KV cache stays local and nothing is copied per turn. Bound concurrency by KV-cache bytes, not by request count: a replica admits a new session only if its cache budget allows. Give every session an idle TTL and evict on expiry or on client disconnect. Make each turn idempotent with a client-supplied turn sequence number, so a retry after a timeout does not append the prompt twice. On replica loss the session is gone: the client restarts the sequence. Do not migrate the cache unless the session is long-lived enough that rebuilding it costs more than moving it.

Sizing the cache. Per-token KV bytes = 2 × n_layers × n_kv_heads × head_dim × dtype_bytes. For a 32-layer model with 8 KV heads (GQA), head dim 128, fp16: 2 × 32 × 8 × 128 × 2 = 131,072 B = 128 KiB per token. An 8,192-token session holds 1 GiB. On an 80 GB H100 with roughly 60 GB left for cache after weights and activations, that is about 60 concurrent sessions. This number sets your admission limit and your autoscaling target, not requests per second.

Trade-offs.

ApproachSurvives replica lossCost per turnUse when
Sticky cache on the replicaNo~0, cache stays in HBMDefault; sessions are short or cheap to rebuild
Externalize KV to CPU or NVMeYes~1 GiB over PCIe 4.0 x16 ≈ 40 ms plus deserializeLong sessions where a rebuild takes minutes
Recompute from the promptYesFull prefill, roughly 100–200 ms for 8k tokens on a 7BSessions are short and storage is the bottleneck

Sticky routing is the default because the alternatives cost an order of magnitude more per turn. Externalize only when rebuild cost exceeds transfer cost.

Failure modes and how to detect them.

  • Duplicate append on retry. The client times out, retries, and the replica has already advanced the cache: the prompt is applied twice, output drifts, and the cache grows to 2×. Guard with a per-session last_applied_seq and reject or replay any turn with seq ≤ that. Alert on the counter of rejected duplicates: a spike means your timeout is shorter than your p99 turn latency.
  • Eviction mid-sequence. The idle TTL fires while the client is slow. The next turn pays full prefill: p50 turn latency jumps from ~15 ms to ~150 ms. Track a "continuation cache miss" counter and alert above ~1%.
  • Hot spot. Consistent hashing sends 3× the sessions to one replica. Watch per-replica session count and KV utilization; fix with bounded-load hashing (pick two replicas, take the less loaded) instead of plain modulo.
  • Abandoned sessions. A client disconnects mid-stream and the slot is held until TTL. A churn of aborts exhausts the cache while GPU utilization looks low. Free the slot when the stream closes, and track sessions with no active stream.

Turn handler.

Python
# Python 3.12, illustrative
def handle_turn(session, turn_seq, prompt_tokens):
    if turn_seq <= session.last_applied_seq:
        return session.cached_response(turn_seq)      # idempotent retry
    if session.kv_bytes + estimate(prompt_tokens) > session.budget_bytes:
        raise SessionEvicted(session.id)              # client restarts
    out = model.generate(prompt_tokens, kv_cache=session.kv_cache)
    session.last_applied_seq = turn_seq
    session.touch()                                   # reset idle TTL
    return out

Trace: turn_seq=5 with last_applied_seq=5 returns the cached response and never touches the model. turn_seq=6 passes the budget check, generates, sets last_applied_seq=6, and resets the TTL. A retry of turn 6 after a timeout hits the first branch, so nothing is appended twice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design prediction caching safely.

Answer

Assumptions I'd state first. An online prediction service, multi-tenant, where model inference dominates request latency, and where each use case has an owner who can name a staleness tolerance. If nobody can name that tolerance, the answer is "don't cache yet": you can't set a TTL you can't defend.

Core answer. Cache a prediction only when the same inputs provably produce the same output, and put every input that can change the output into the key: tenant, model id and version, feature/preprocessing version, the canonicalized feature vector, and policy context (region, consent state, experiment arm). Set TTL to the minimum of the staleness tolerance and the revocation SLA. Bypass the cache entirely for non-deterministic paths (sampling, LLM decode) and safety-critical decisions (fraud block, triage).

Why the key looks like that. A preprocessing change, say a new normalization, shifts the input distribution. A cached score computed under the old pipeline gets served as if it came from the new one, and nothing in the response reveals the swap; that's silent score skew, and the only cheap fix is the feature version in the key. Model version matters for the same reason during a canary: cached scores from the previous model contaminate the canary cohort's metrics, so either version is in the key or you flush at rollout. TTL is the worst-case window you keep serving a result after consent is withdrawn or a model is pulled. If the revocation SLA is 5 minutes, a 24-hour TTL is a compliance bug, not a performance choice, which is why you also keep a purge index (key → entry) so you can delete on demand instead of waiting out the TTL.

Python
# Python 3.12
import hashlib, json

def cache_key(tenant_id, model_id, model_version, feature_version,
              feature_vector, policy_ctx):
    payload = json.dumps({
        "t": tenant_id,
        "m": f"{model_id}:{model_version}",
        "fv": feature_version,
        "f": feature_vector,        # ordered, canonicalized
        "p": policy_ctx,            # {"region": "eu", "consent": "ads-v2"}
    }, sort_keys=True, separators=(",", ":"))
    return "pred:" + hashlib.sha256(payload.encode()).hexdigest()

Log the tenant, model version and a short digest prefix: never the payload, which holds the feature vector and whatever PII rode in with it.

classexampleTTLbypass
batch scoringnightly risk score24 h—
interactive rankingfeed ranking60 sreal-time features present
safety decisioningfraud block, triagenonealways recompute
non-deterministicsampled decodenone—

Arithmetic (hypothetical, to show the trade). 12k rps ranking, 85% hit rate, 1.2 ms cache read vs 45 ms inference: ~10.2k inferences/s saved. But if 2% of hits are stale beyond tolerance, that's 240 stale decisions/s: that number, not the hit rate, decides whether the TTL is right.

Failure modes to detect. Missing tenant in the key → cross-tenant read; detect with a per-tenant key-prefix assertion in tests. Cold-start stampede → single-flight the miss so one request recomputes and the rest wait. Negative caching of errors → a transient failure pinned for the whole TTL; cache successes only. TTL longer than the revocation SLA → purge-index lag alarm.

Trade-offs. Per-tenant isolation costs memory; a shared cache is cheaper but one key bug becomes a breach. Longer TTL saves more compute and widens the stale window. Cache the cheap, stable, high-volume path; recompute the rare, safety-relevant one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Introduce quantization without silently degrading users.

Answer

Core answer

Pin two things before touching precision: which resource is actually the bottleneck, and which slice of traffic is not allowed to regress. Assumptions I would state out loud - an LLM behind one API, a frozen eval set that already covers the protected slices, and permission to run two artifacts side by side during a canary window.

  • Decode latency at low batch is a weight-byte problem. Weight-only 4-bit (W4A16: GPTQ or AWQ) is the move, activations stay FP16.
  • Maximum concurrent sequences is a KV-cache problem. An FP8 KV cache halves the bytes; vLLM exposes this as kv_cache_dtype=fp8 (also fp8_e4m3 / fp8_e5m2).
  • Prefill throughput on H100 is a compute problem, and there FP8 weights plus activations usually beats INT8, because the exponent field tolerates activation outliers that a single per-tensor INT8 scale cannot.
movewhat it quantizeswhat it buysmain failure mode
W4A16, group size 128, per-group FP16 scalesweights only~4x smaller weights, decode-bound throughputweight error compounding across layers; calibration mismatch
W8A8 (SmoothQuant-style)weights and activationsprefill and decode on INT8 tensor coresone outlier channel sets the activation scale for every channel
FP8 KV cacheK and V tensorslong-context and large-batch memorylong-context recall, needle-in-haystack tasks

Why the same change helps one slice and hurts another

Weight-only error is roughly uniform per weight, so it lands as small logit noise everywhere. That is benign until an output is decided by a near-tie: a JSON key, a function name, one digit of an account number, a citation marker. The aggregate score moves 0.2 points while the code slice's pass@1 drops several, because those outputs are all-or-nothing - one wrong character fails the sample.

W8A8 fails differently, and this is the part worth saying out loud. Calibration measures activation ranges on a sample set and derives the scales. A few feature dimensions carry outliers far above the median; LLM.int8() exists precisely to pull those dimensions out into FP16 rather than pretend they are not there. With one per-tensor scale, that max sets the step size for every channel, so the error concentrates in the many ordinary, small-magnitude channels. The ranges are also only right for the data you calibrated on: calibrate on generic English and serve code with long identifiers, and the scale is fitted to the wrong distribution. GPTQ's paper used 128 calibration sequences of 2048 tokens drawn from C4; recipes in practice run 128-512 samples, and matching the serving distribution matters more than the count. AWQ takes a different route - it protects the weight channels with the largest activation magnitude (the paper puts the salient fraction around 0.1-1%) with per-channel scaling chosen by grid search, no backprop.

The gate, with numbers

Memory arithmetic for a 7B model with full MHA (32 layers, 32 KV heads, head_dim 128):

  • Weights FP16: 7e9 * 2 bytes = 14 GB. INT8: 7 GB. 4-bit group-128: ~3.6 GB including the FP16 scales (2 bytes per 128 weights adds ~109 MB).
  • KV per token per layer: 2 * 32 * 128 * 2 bytes = 16 KB. Across 32 layers: 512 KB per token. An 8K context is 4 GB per sequence; FP8 halves that. GQA models cut the KV head count and start far lower.

Sample-size arithmetic: to detect a 2-point absolute regression in a slice rate at 95% confidence, n = (1.96 / 0.02)^2 * 0.25 = 2401, so about 2,400 sampled requests on that slice (worst case, rate near 0.5). A protected slice seeing 50 requests a day cannot be judged from production traffic at all - it has to be a fixed set of cases in the offline eval.

Promotion rule: block if any protected slice drops more than the eval's noise floor (roughly 2 standard errors, recomputed per slice), if top-1 agreement with the FP16 model on a 500-request shadow stream falls below the band the FP16-vs-FP16 control establishes, or if JSON parse rate or tool-call schema validity moves at all. A gain that depends on breaking a rare or protected slice does not ship.

Watching it live, and when not to do it

Serve both artifacts, sample 1 in N requests, and compare top-1 agreement, KL on the top-k distribution, structured-output validity, and per-slice task metrics. Rollback is repointing the router at the FP16 artifact, which means it stays loaded through the canary window - budget that extra memory in the rollout plan, because it is the memory you were trying to reclaim.

Three cases where I would not quantize: prefill-bound workloads get almost nothing from weight-only quantization; models used for arithmetic or as a judge are a bad 4-bit trade; and if the SLO is already met, you are adding a failure mode for free. On H100, try FP8 before INT8.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How do you manage KV cache memory allocation and fragmentation using PagedAttention in high-throughput LLM serving?

Answer

In autoregressive LLM serving, KV cache memory scales dynamically per request with token sequence length ($2 \times 2 \times n_{\text{layers}} \times n_{\text{heads}} \times d_{\text{head}} \times \text{precision}$ bytes per token). Standard GPU allocators require contiguous virtual memory allocations sized to worst-case sequence lengths (max_model_len), generating up to 60–80% memory waste via internal fragmentation (over-allocating for early tokens) and external fragmentation (gaps between variable-length requests).

PagedAttention resolves this by borrowing the virtual memory page table paradigm from operating systems. KV cache storage is pre-allocated into fixed-size physical blocks on the GPU (typically 16 or 32 tokens per block). Each logical request maintains a block table mapping sequential token positions to non-contiguous physical block addresses.

KV Cache Size Arithmetic

For a 70B parameter model with 64 layers, 8 KV heads (Grouped-Query Attention), head dimension 128, and FP16 (2 bytes):

  • Per token per layer: $2 \times 8 \times 128 \times 2\text{ bytes} = 4{,}096\text{ bytes} = 4\text{ KiB}$
  • Per token across 64 layers: $4\text{ KiB} \times 64 = 256\text{ KiB}$
  • A 4,096-token sequence: $256\text{ KiB} \times 4{,}096 = 1\text{ GiB}$ per request.

With contiguous allocation, a batch of 64 requests pre-allocating 4,096 slots requires $64\text{ GiB}$ regardless of actual generation length. With PagedAttention (block size = 16 tokens, $4\text{ MiB}$ per block), physical blocks are allocated on-demand during decoding. Internal fragmentation is bounded strictly to the final incomplete block ($< 16$ tokens, or $< 4\text{ MiB}$ per request).

Block Allocation & Copy-on-Write

Logical Tokens:   [T0..T15]  [T16..T31]  [T32..T47]  [T48..T63]
                     |           |           |           |
Logical Block ID:    0           1           2           3
                     v           v           v           v
Block Table:      [Phys 12]   [Phys 4]    [Phys 99]   [Phys 7]
                     |           |           |           |
Physical GPU Mem: [Block 4]   [Block 7]   [Block 12]  ...  [Block 99]
  1. Dynamic Expansion: During decode iterations, when a new token crosses a 16-token boundary, the scheduler pops a free block index from the pre-allocated free pool and appends it to the request's block table. If no blocks are free, the engine must either preempt (recompute or swap to host RAM) or throttle admission.
  2. Prefix Sharing & Forking: Parallel sampling (best-of-N, beam search) and system prompt sharing share physical block pointers with a reference count. When branching paths write new tokens into the final block, Copy-on-Write (CoW) duplicates only that block.

Memory Management Comparison

MechanismContiguous Pre-allocationPagedAttention (Virtual Paging)
Allocation TimingUpfront at request admission (max_len)On-demand at block boundaries (e.g., every 16 tokens)
Memory FragmentationHigh (60–80% internal + external)Near-zero (internal bounded to $<1$ block per stream)
Parallel SamplingDuplicates prompt KV cache across forksShares physical blocks via reference counting + CoW
Preemption MechanismCancel entire request or abortEvict blocks to CPU host memory or recompute tokens
Max Concurrent BatchLow (constrained by reserved memory)High (saturates GPU compute memory bandwidth)

Failure Modes and Mitigations

  • GPU Memory Thrashing under Preemption: When GPU block pools saturate during decoding surges, the scheduler must preempt requests. Evicting KV blocks to host RAM adds PCIe transfer latency (~32 GB/s on PCIe Gen4 vs ~2–3 TB/s HBM); recomputing causes tail latency spikes. Mitigation: Pair with continuous/iteration-level scheduling, enforce admission control based on available free blocks rather than simple concurrency counts, and reserve a 5–10% block buffer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Why and how do modern LLM inference architectures disaggregate prefill and decode stages across distinct GPU clusters?

Answer

Prefill and decode exhibit opposite hardware bottlenecks. Colocating both phases within the same GPU engine (e.g., standard continuous batching in Triton Inference Server or vLLM engines) creates resource contention and tail-latency degradation: long context prefill monopolizes matrix execution units (Tensor Cores), stalling time-to-first-token (TTFT) and interrupting iterative decode steps, which spikes inter-token latency (ITL / TPOT).

Bottleneck Divergence

  • Prefill (Prompt Processing): Compute-bound. Operates on full sequences ($N$ prompt tokens simultaneously) via General Matrix Multiplies (GEMMs). Arithmetic intensity is high (hundreds of FLOPs/byte), achieving 60-80% peak Tensor Core utilization.
  • Decode (Token Generation): Memory-bandwidth-bound. Operates on batch size $B$ with sequence length 1 via General Matrix-Vector products (GEMVs). Every step reads weights and entire accumulated KV caches ($2 \times L \times H \times D \times \text{precision}$) from High Bandwidth Memory (HBM) for only one token output per sequence, running at fractional compute utilization (often <5% peak FLOPs).
PhasePrimary MetricDominant BottleneckOptimal Hardware StrategyTypical Batching Dynamic
PrefillTime-To-First-Token (TTFT)Tensor Core compute (FLOPs/s)High FP8/FP16 TFLOPs; aggressive Tensor Parallelism ($TP$)Large token chunks (e.g., 4096-8192 tokens/batch)
DecodeInter-Token Latency (ITL / TPOT)HBM Memory BandwidthMaximum memory bandwidth (TB/s); Pipeline/Data ParallelismDeep batch sizes ($B=128-512$) using PagedAttention

Disaggregated Architecture & Pipeline

Client Request
      │
      ▼
[ Global Router / Scheduler ]
      │
      ├── 1. Dispatch prompt tokens
      ▼
[ Prefill Worker Cluster ] ── Compute-bound (Large GEMM, TP=4/8)
      │
      ├── 2. Transfer KV Cache via InfiniBand / RoCE (RDMA bypass)
      ▼
[ Decode Worker Cluster ]  ── Bandwidth-bound (GEMV, Large Batches, TP=1/2)
      │
      └── 3. Stream generated tokens directly to client
  1. Front-End Router / Dispatcher: Receives requests and schedules prefill across a compute-optimized pool. Computes routing decisions based on current decode worker KV cache allocations.
  2. Prefill Execution & Cache Allocation: The prefill node processes prompt tokens in large contiguous chunks, computes attention keys/values, and holds the KV blocks in GPU memory.
  3. KV Cache Transfer (Inter-Cluster State Synchronization): The prefill engine transmits layer-by-layer KV cache tensors to assigned decode nodes over a dedicated RDMA network (InfiniBand or RoCE v2). Transport must use GPU Direct RDMA (GDDR) to avoid host staging overhead. $$\text{Transfer Volume} = 2 \times \text{Layers} \times \text{Heads}{KV} \times d{head} \times N_{prompt} \times \text{bytes/param}$$ Worked sizing: A 70B model (e.g., Grouped Query Attention with 8 KV heads, head dimension 128, 80 layers in FP16) requires $2 \times 80 \times 8 \times 128 \times 2 = 327,680\text{ bytes/token}$ ($320\text{ KB/token}$). For a 4,096-token prompt, KV transfer size is $\approx 1.31\text{ GB}$. Over an 800 Gbps (100 GB/s) InfiniBand interconnect, transfer takes $\approx 13.1\text{ ms}$, which overlaps cleanly with chunked prefill or final-layer generation.
  4. Independent Autoscaling: Decode pools scale out based on concurrency and token throughput metrics (nv_inference_request_duration_us, KV memory utilization); prefill pools scale on queue depth and TTFT p99 via Kubernetes HPA or KServe Custom Metrics.

Failure Modes & Edge Cases

  • Network Transfer Outweighing Compute: If prompts are short ($N < 256$) and interconnect bandwidth is limited (e.g., 100 Gbps Ethernet without GPUDirect), network transfer latency exceeds prefill execution time, making disaggregation slower than colocation. Implement dynamic threshold routing: requests under $N_{threshold}$ execute on colocated nodes.
  • Decode Memory Stranding & Fragmented Allotment: Prefill completes faster than decode capacity opens up, causing the prefill cluster to stall on KV offloading. Mitigate via unified virtual memory managers (e.g., virtualized paged KV blocks across prefill/decode) and speculative pre-reservation at the router before prefill initiates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Evaluate a CPU-to-GPU serving migration.

Answer

I’d run this as a controlled A/B on the same versioned contract, not a hardware swap. The decision rule: migrate only if GPU improves end-to-end p99 at the SLO and cost per useful prediction after transfer, preprocessing, batching, and quota. Otherwise stay CPU.

Assumptions: same model weights and version, same preprocessing, same output tolerance and slice quality on the same validation set, replay of production shapes and concurrency, and a fixed SLO (say p99 < 100 ms, error rate < 0.1%). If any of those change, the comparison is invalid.

Measure on CPU (16 vCPU), T4 (16 GB, 70 W), A10 (24 GB, 150 W) with identical containers. Hypothetical numbers for a 5 ms model kernel:

metricCPU 16 vCPUT4A10
p50 latency, batch 130 ms12 ms8 ms
p99 latency, batch 1120 ms45 ms30 ms
throughput at p99<100ms260 req/s900 req/s1,400 req/s
cost/hr$0.80$0.35$1.00
cost per 1M useful preds$0.85$0.11$0.20

The mechanism: GPU latency differs because each request pays PCIe transfer and kernel launch. Batching amortizes transfer over the batch. With max batch delay 5 ms and batch 8, transfer 2 ms + kernel 5 ms = 7 ms per batch, so 8 requests in 7 ms plus up to 5 ms queueing. That gives ~1,140 req/s and p99 ~12 ms. At batch 1, transfer and launch dominate, so GPU can be slower than CPU for small models. Utilization matters because GPU cost is per hour: at 10% utilization, cost per useful prediction is 10x worse. CPU can scale down or share.

Failure modes: OOM under batch growth when max batch size exceeds memory; detect via GPU memory metrics and batch-size histogram, alert at 80% memory. Driver/CUDA mismatch after node upgrade; detect via canary and version check. Cold-start storms when autoscaling GPU nodes; detect via p99 spike and queue depth. Node loss; detect via health checks and fallback to CPU pool. Each has operational cost: GPU nodes are scarcer, so fallback capacity must be provisioned.

Tradeoffs: GPU not worth it when QPS < 200, batch size 1, p99 SLO < 20 ms, or model already meets SLO on CPU. GPU worth it when QPS > 500, batch >= 8, throughput-bound, and cost per useful prediction drops > 2x. T4 vs A10: T4 cheaper per hour but less memory and compute; A10 wins if batch > 16 or model > 10 GB. CPU wins when traffic is spiky and you can scale to zero.

Worked check: CPU at 260 req/s costs $0.80/hr = $0.000000855 per request = $0.85 per 1M. T4 at 900 req/s costs $0.35/hr = $0.000000108 per request = $0.11 per 1M. A10 at 1,400 req/s costs $1.00/hr = $0.000000198 per request = $0.20 per 1M. If T4 only reaches 300 req/s because batch stays at 1, its cost per 1M is $0.32, still better than CPU but p99 may fail. If it reaches 100 req/s, cost per 1M is $0.97, worse than CPU.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Choose a fallback for a high-stakes prediction service.

Answer

Assume the service makes a decision with a deadline and money or rights on the other side of it: a payment authorization, a claims triage, a loan pre-approval, a content takedown. The fallback is not one decision. It is one per failure class, and the classes have different correct answers. Answer directly, then earn it.

The short answer. There is no global default prediction. Default to fail closed with a typed unavailability result, and open specific exceptions where a real degraded answer exists: a pinned previous approved model for outages, stale cache for slow-moving features, delayed processing where the deadline is hours, human review where volume allows. Never return a neutral score.

Classify before you choose. Two questions decide it: did the primary fail to produce an answer, or produce one you do not trust? And can a human act before the deadline expires?

failurefallbackcaller seesdetection signal
timeout, model host down, deadline < 1 spinned previous approved model, else fail closeddeny today, retry afterfallback_rate by reason, model_version
feature lookup miss, slow featuresstale cache only if the feature is slow-moving (banding, not velocity), else fail closeddecision plus degraded flagfeature_age_seconds, cache_hit
score inside the ambiguity bandhold for human reviewpending, reviewed within SLAqueue depth, age of oldest item
batch, or deadline in hoursdelayed processing, same model, next windowanswer arrives laterbacklog, time-to-decision
required policy or unapproved model versionfail closed, page the ownerexplicit unavailabilitypolicy_block counter

Why the neutral score is the trap. A fallback returning 0.5 is consumed downstream as a prediction. Illustrative numbers: if the approve threshold is 0.4, a 0.5 fallback silently approves 100% of failures, and your failure rate quietly becomes an approval rate. Return a typed result the caller must handle - {"status": "unavailable", "reason": "feature_timeout"} - not a float. If your API contract can only express a float, that contract is the bug, not the fallback.

Do the capacity arithmetic before promising human review. Worked example, illustrative: 2,000,000 decisions/day, 0.5% fail or land in the ambiguity band = 10,000 escalations/day. At 3 minutes per review that is 500 reviewer-hours/day; at 6 productive hours per shift, ~84 reviewers, staffed overnight if traffic is flat. Human review is a good fallback below roughly 1,000 escalations/day (50 hours). Above it you are choosing between fail closed and a better model, not between a model and people.

Keep each rung inside the deadline. Primary p99 300 ms against an 800 ms SLA leaves 500 ms for a retry, which fits the same model again; a slower secondary at 600 ms p99 does not. Order the ladder by cost and check every rung against remaining budget.

Python
def decide(features, deadline_ms=800):
    t0 = time.monotonic()
    try:
        r = primary.predict(features, timeout_ms=remaining(t0, deadline_ms))
    except Timeout:
        if prior_model.ready():            # previous approved version, still deployed
            r = prior_model.predict(features, timeout_ms=remaining(t0, deadline_ms))
            return Result(r.score, "ok", reason="prior_model", version=prior_model.version)
        return Result(None, "unavailable", reason="primary_timeout")
    if AMBIG_LO <= r.score <= AMBIG_HI:    # band set from your cost curve, not 0.5
        return Result(r.score, "pending_review", reason="ambiguity_band")
    return Result(r.score, "ok", version=primary.version)

The three failure modes worth naming. Silent fallback growth: the primary degrades tenfold and nobody notices because the fallback keeps returning 200s, so make fallback_rate an SLO with a multi-window burn-rate alert, not a dashboard line. Training on your own fallback: if fallback scores reach the label store without a reason code, the next model learns the fallback's policy - stamp fallback_reason and the producing version on every decision and exclude those rows from training. Stale cache surviving a distribution shift: invalidate on schema change and alert on cache age p99, not hit rate.

One position to take in the room: no single default, and never a default that looks like a prediction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Measure cost efficiency for model serving.

Answer

What I'd say in the first 90 seconds

Define the unit before you measure anything. Cost efficiency = dollars per successful prediction that met both its latency SLO and its quality bar. Accrued cost goes in the numerator whether or not the request succeeded: accelerator time, host CPU, memory, storage, egress, observability, and replicas kept warm but idle. Only correct, on-time answers go in the denominator. That asymmetry is the whole point: a system that sheds its slowest 10% of traffic looks cheaper under any other definition.

Assume GPU replicas billed by the hour, multiple models and tenants sharing them, and a p95 time-to-first-token (TTFT) SLO the product actually measures against.

Why the ratio behaves the way it does. You rent accelerators by the hour, not by the token. So marginal cost per token is instance price per hour divided by achieved tokens per hour. Throughput is the dominant lever, and continuous batching is the biggest single source of it: a single stream at batch 1 leaves most of the SM array waiting on memory bandwidth, while ~32 concurrent sequences overlap that wait.

Worked arithmetic (illustrative, one $2.00/hr replica)

configaggregate output tok/s$ per M output tokens
single-stream, batch 1, FP165011.11
continuous batching, ~32 concurrent1,2000.46
plus INT8/FP8 weights1,8000.31
1.5B model, same batch, only if it clears eval3,0000.19

Row 1: 50 tok/s * 3600 s = 180,000 tokens/hr, $2.00 / 0.18M = $11.11 per million. Row 2: 1,200 * 3600 = 4.32M, $2.00 / 4.32M = $0.46. Same hardware, same weights, 24x apart on batching alone.

Those figures assume the replica stays busy. Provisioned for peak, a replica averaging 20% utilization delivers a fifth of that throughput, so row 2's real cost is 0.46 * 5 = about $2.30 per million. That is why the headline number is never reported alone: pair it with average GPU utilization and queue wait.

What to instrument

Per request, record model and version, tenant, prompt tokens, output tokens, queue wait, prefill ms, decode ms, batch size at admission, prefix-cache hit, terminal status, retry count, and whether the SLO was met. Roll up as tokens * the per-token rate of the accelerator the request landed on, then add amortized idle and non-accelerator overhead allocated by GPU-seconds for co-located models and by request share for shared CPU. vLLM emits per-request timing and does the continuous batching above; DCGM gives SM utilization; Prometheus plus Grafana carry the rollup.

Trade-offs and failure modes

  • Raising batch size buys throughput at the cost of TTFT. The ratio improves while the SLO breaks silently: detect by watching TTFT p50 diverge from p99 and by bucketing queue wait.
  • Warm capacity for fast scale-from-zero: utilization under about 5% with replicas above zero is the signature. Fix with a cheaper keep-warm path, not by dropping the warm pool.
  • Quantization clears latency and fails quality. Gate it on the offline eval suite before shipping, and watch regeneration and thumbs-down rates online.
  • Retry storms: a 10% failure rate with full retries adds roughly 11% to cost invisibly. Track cost per attempt alongside cost per completion.
  • Attribution drift when tenants are billed by wall-clock instead of measured GPU-seconds on a shared node.

Batch-mode and async endpoints are the right call for non-interactive traffic, where latency headroom converts directly into tokens per hour. A smaller model is only a cost win if it passes the same eval bar; otherwise you have moved cost from the accelerator to the product.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Define success metrics for an inference platform.

Answer

I'd start by fixing the unit of value: a served decision a downstream consumer actually used, not a request that returned 200. Three assumptions I'd state out loud: we own the serving path, not training; each workload class carries its own latency SLO; and we can join predictions to delayed outcomes within about a day. Then I'd report three tiers.

Tier one is goodput: the fraction of requests that returned a valid prediction inside the deadline. That one number beats availability, because a service answering in 3 s against a 200 ms SLO is up and useless. Report it at p50 and p99, per workload class.

Tier two is platform health: queue wait, rejection, fallback, cold start, model-load success, feature freshness.

Tier three is economics and quality: cost per useful prediction, and quality sliced by model version, input segment, and delayed outcome.

Why the tail and not the mean. A single worker with 20 ms service time at 40 req/s sits at ρ = 0.8, and M/M/1 wait is ρ/(1−ρ) × service ≈ 80 ms, so mean latency is ~100 ms. Push to 45 req/s, ρ = 0.9, wait ≈ 180 ms, mean ~200 ms. A 12% traffic bump doubles the mean and shoves p99 past a 200 ms deadline. Mean latency hides that; the tail is where the SLO lives.

Rejection is the same mechanism seen from the other end: admission control drops requests once queue wait exceeds the max batch wait, so rejection rate is a capacity signal, not a client signal.

MetricWhy it's the one to watchDetection signal (hypothetical targets)
Goodput @ p99value actually deliveredalert < 99.5% over 5 min
Queue wait p99leading indicator of deadline missesalert > 50 ms
Rejection rateadmission control firingalert > 0.1%
Fallback rateavailability propped up by a degraded pathalert > 1%, page > 5%
Cold-start p99new replicas serving slowalert > 2x steady-state p99
Feature age p99stale inputs degrade quality silentlyalert > 2x refresh interval
Cost per 1k useful predictionsties spend to valuealert on 20% week-over-week rise

Cost per useful prediction, worked: 8 accelerator replicas at roughly $3/hr is $24/hr. At 1M predictions/hr and 60% usefulness, that's 600k useful decisions, or $40 per 1k. If usefulness slips to 45%, it's $53 per 1k: a 33% cost regression raw QPS never shows.

Failure modes, each with a signal:

  • Silent quality drift. Detect with PSI > 0.2 on the top-20 features against the training baseline; blast radius is every request on that version.
  • Fallback masking. Tag fallback responses and slice quality by the flag. At a 3% fallback rate with fallback quality at 70% of primary, blended quality drops ~1%: invisible in aggregate, visible in the slice.
  • Cold start. A replica loading weights for 45 s serves at ~10x steady-state p99 for its first ~100 requests; watch readiness-probe duration and per-replica first-100 p99.
  • Feature staleness. A feature store returning last-known values degrades quality with no error; alert when max feature age exceeds 2x the refresh interval.

Trade-offs. Goodput is stricter and harder to game than availability; use it as the SLO and report availability as context. And a single-model, single-tenant service with no delayed labels doesn't need the slice-and-lineage machinery: p99 latency, error rate, and a weekly offline quality sample suffice. The full set pays off only with multiple versions, tenants, or an audit requirement. What I'd never put on the dashboard alone: raw QPS, replica count, or accelerator utilization. All three reward waste.

Curated: · Written: · Reviewed:

Difficulty: Hard