On this page
At minute twelve of an AI lab system design round, your whiteboard holds an API gateway, GPU workers, and a vector index. Then the interviewer asks: an under-quota tenant hits a queue that will miss its first-token SLO. What status code returns, which stage owns that call, and what trace lets on-call engineers inspect it? Giving every box a numeric budget, an owner, a decision trace, and a recovery path turns boxes into an architecture.
In AI Lab Coding Interview: Python Systems, we built single-node KV allocators and batch loops; here that ownership scales to distributed inference. We carry one product throughout: an internal multi-provider model gateway, then layer on permission-aware retrieval and a long-running coding agent as follow-ups. OpenAI's public interviewing guidance emphasizes clear reasoning adapted to the role, so confirm scope with your recruiter.[1]
Start with a constraint
Begin with one dominant constraint and earn every box: keep the first sketch small, size the main bottleneck early, and add queues, caches, or sharding only when required. Walk ten beats in order:
- Goal: caller and success metric.
- Requirements: behavior plus latency, freshness, and privacy targets.
- Scale: QPS, tokens, tenants, docs, latency, retention.
- API: external API schema and internal interfaces.
- Data model: durable entities, indexes, tenant isolation.
- Architecture: smallest working request path.
- Reliability: retries, idempotency, backpressure, load shedding, failover.
- Security and safety: permissions, traces, abuse limits, fast reverts.
- Observability: metrics, logs, traces, support lookup.
- Deployment: beta flags, canaries, eval checks, kill switches.
Let the pressure choose the pattern
One dominant pressure anchors the first sketch:
| Pattern | Signal | Core moves | Follow-up pressure |
|---|---|---|---|
| Model gateway | multi-provider, keys, quotas | auth, entitlements, routing, quota buckets, trace | streaming, fallback opt-in, spend caps |
| Inference scheduler | latency, GPUs, overload | bounded queue, batcher, KV accounting | tail latency, preemption, 429/503 |
| Enterprise retrieval | docs, ACLs, citations | connectors, ACL snapshots, pre-retrieval filter | revocation lag, fail closed, tombstones |
| Agent platform | long tasks, repo writes | state machine, sandbox, tool allowlist | cancellation, retries, secret redaction |
| Eval and release | launch checks, red team | offline suites, canary controller, rollback | slice drops, typed metric checks |
Our gateway earns retrieval only when private documents enter the prompt, and an agent state machine only when tasks run repository side effects.
Let follow-ups move a boundary
Name what shifted, which stage owns it, and how telemetry verifies it:
| Follow-up | Strong move | Weak move |
|---|---|---|
| "Traffic spikes 10x" | rate limits, wait cap, tier fairness, 429/503 | unbounded queues |
| "Permissions change fast" | ACL freshness cap, tombstones, fail-closed sources | retrieve then filter |
| "Provider is down" | opted-in fallback, circuit breaker, degraded notice | silent model swap |
| "Users cancel mid-run" | durable cancel intent, cooperative stop, sandbox kill | UI-only stop button |
| "Support asks why" | request ID, config version, route, retrieved IDs | raw unstructured logs |
| "Eval passes, users complain" | slice analysis, canary metrics, regression case | trust offline average |
Put one number on the board
Write one load-bearing calculation with explicit units, note what it omits, and state which layer changes at 5x load: gateway (RPM, TPM, max output), retrieval (docs, chunks, index bytes, ACL refresh), scheduler (arrival rate, service time, queue wait, HBM), or agent service (concurrent sandboxes, duration, artifact bytes).
Size model memory before drawing workers
Once self-hosted GPUs enter, put fixed weights () and linear KV cache (, summed across active lengths ) on the board. For the full memory and bandwidth derivation, see Inference Mechanics: TTFT, TPS, and KV Cache. Keep decimal GB () distinct from GiB (), and leave headroom for activations, workspaces, and block rounding.
For an 8B BF16 model (32 layers, ) at batch 16 and 2,048 tokens, weights occupy 16.0 GB, multi-head attention (32 KV heads, 524,288 B/token) needs 17.2 GB, and Llama 3 8B's GQA (8 KV heads, 131,072 B/token) cuts KV to 4.3 GB (an architecture choice, not a runtime flag).[2][3]

Leave a decision trail
| Decision | Chosen | Rejected | Reversal signal |
|---|---|---|---|
| Queue placement | before provider call | inside each adapter | adapter-specific SLO |
| Retrieval ACL | before rerank/generation | post-generation filter | none for sensitive docs |
| Fallback model | explicit opt-in | silent auto-swap | customer opt-in |
| Agent repo writes | patch + human review | direct branch push | reversible narrow scope |
Rehearse the board as a sequence
Front-load the dominant constraint and bottleneck math so the second half covers failure modes rather than basic boxes.
Deep dive: 45-minute whiteboard pacing
| Window | Output |
|---|---|
| 0-9 min | goal, users, success metric, functional/non-functional bounds |
| 9-14 min | one scale calculation exposing the main bottleneck |
| 14-28 min | API, durable data model, smallest working request path |
| 28-40 min | overload (429/503), ACLs, support trace, eval/canary release |
| 40-45 min | tradeoffs, reversal signals, follow-ups |
Turn requirements into boundaries
Name the user, promise, and clarifying questions that alter architecture before expanding each blueprint.
Prompt 1: model gateway for enterprise teams
Internal multi-provider LLM gateway enforcing API keys, entitlements, RPM/TPM/spend caps, beta flags, and support request IDs under 10x spikes. Ask: streaming vs. batch mix, hard vs. soft spend caps, top support failure.
Deep dive: Model gateway blueprint
- API & data:
POST /v1/responses,GET /v1/requests/{id}; org, workspace, key, routing config, entitlement, usage bucket, request trace. - Path & overload: gateway -> auth -> atomic quota reservation -> routing -> bounded queue -> adapter -> stream;
429caller quota,503shared saturation, groundedRetry-After.
Prompt 2: permission-aware enterprise retrieval
Internal Q&A over heterogeneous ACL sources with fast revocations, citations, zero post-generation filtering, and admin eligibility traces. Ask: revocation freshness target, tenant index isolation, fail-closed sensitive sources.
Deep dive: Retrieval blueprint
- Index & query: immutable doc versions + ACL snapshots + immediate deletion tombstones; query runs auth -> freshness + eligible filter -> hybrid search -> rerank -> cited answer, failing closed on stale ACLs.
Prompt 3: long-running coding agent service
Async coding agent (up to 30 min) with live progress streams, cancellation, diff review, and isolated secrets. Ask: patch artifact vs. direct push, network egress, mid-tool cancellation.
Deep dive: Coding agent blueprint
- State & isolation:
queued -> provisioning -> running -> blocked / review -> failed / canceled / complete; scoped sandbox, short-lived creds, log redaction; reconcile timed-out writes unless receiver idempotency is verified;[4] separate cancel intent from confirmed exit.
Request admission owns overload
Mint a server-generated request_id before auth so rejected calls stay traceable. Authenticate, check entitlements, atomically reserve quota, and check shared capacity: over-quota callers get 429 even on idle GPUs; eligible callers hitting a full fleet get 503.[5][6]

Aggregate demand sizes the fleet, while hard spend caps require per-request atomic reservations (input + max output at upper-bound tariffs, since prompt cache writes can cost more than uncached input[7]), reconciling confirmed usage strictly once per request_id and holding disconnected reservations pending until settlement:
tpm = 4_000 * (1_200 + 450)
tps, cap = tpm / 60, 125_000
bal, res, actual = 10_000, 1_800, 1_520
print(f"tpm={tpm:,} tps={round(tps):,} headroom={round(cap - tps):,} ({(cap - tps) / cap * 100:.1f}% unused)")
print(f"quota: after_reserve={bal - res:,} refund=+{res - actual} final={bal - actual:,}")tpm=6,600,000 tps=110,000 headroom=15,000 (12.0% unused)
quota: after_reserve=8,200 refund=+280 final=8,480Queueing changes the latency promise
Letting long prompts onto a busy worker stalls active streams; bound queue depth to protect tail latency. For full queueing and scheduling mechanics, see Inference Mechanics: TTFT, TPS, and KV Cache and Continuous Batching & Request Scheduling.
Separate prefill from decode
Prefill (compute-bound, driving TTFT, skipping cached prefixes[7]) and decode (bandwidth-bound, driving ITL and TPOT) contend on shared GPUs. Chunked prefill caps prompt tokens per step; DistServe defines goodput (requests/s meeting both TTFT and TPOT) and disaggregates prefill and decode pools at the cost of KV transfer bandwidth.[8]
Name the metric that can fail
Always specify metric, percentile, unit, and hardware/workload setup: TTFT (arrival to first token), ITL / TBT (individual inter-token gaps, tracked at p95/p99), TPOT ((t_last - t_first) / (N - 1) for , undefined for 1 token), and goodput / TPS (explicitly per-request vs. fleet aggregate, paired with 429/503 rates and p95/p99 latency).
Choose a serving lever by failure mode
| Lever | Fixes | Reach for it when |
|---|---|---|
| PagedAttention | KV fragmentation | Long contexts exhaust contiguous KV |
| Continuous batching | Idle batch slots | Mixed lengths stall static batches[9] |
| Prefix / radix cache | Repeated prefill | Shared system prompts or history |
| Speculative decoding | Bandwidth-bound decode | Cheap draft yields high acceptance |
| Chunked prefill | Prefill pausing decode | Long prompts spike ITL |
| Disaggregation | Prefill/decode contention | Shared pool misses TTFT + ITL |
Continuous batching governs when sequences join/exit; paged attention governs how KV blocks allocate. Prefix cache hits require both numerical compatibility (exact tokens, positions, model, adapter, layout) and current read access to the private source document.
Model-fit scale math
Map sharding to physical links: TP needs NVLink bandwidth for all-reduces, PP crosses slower links with pipeline bubbles, and EP shards MoE experts.
At 125,000 tok/s, 20,000 queued tokens clear in 0.16 s (<= 0.25 s cap) while 50,000 wait 0.40 s and return 503. Check prefill wait, active decode slots (< max_decode), and free KV blocks (>= needed) atomically before claiming resources (since queue wait is only part of TTFT and concurrent passing checks against one slot must serialize):

can_wait = lambda q, tps, cap: (q / tps) <= cap
can_accept = lambda b, ptps, act, mdec, fkv, nkv, cap: can_wait(b, ptps, cap) and act < mdec and fkv >= nkv
print("20k@125k:", can_wait(20_000, 125_000, 0.25), "| 50k@125k:", can_wait(50_000, 125_000, 0.25))
print("ok:", can_accept(10_000, 80_000, 48, 64, 120, 16, 0.25),
"full:", can_accept(10_000, 80_000, 64, 64, 120, 16, 0.25),
"low_kv:", can_accept(10_000, 80_000, 48, 64, 10, 16, 0.25))20k@125k: True | 50k@125k: False
ok: True full: False low_kv: FalsePermissions belong before retrieval
Post-generation filtering cannot undo a leak once a revoked doc enters an external reranker or prompt. Pair a strict ACL snapshot freshness limit with authoritative revocations (overriding cached grants) and deletion tombstones, failing closed when snapshot age is stale or unknown:

fresh = lambda age, lim: age is not None and 0 <= age <= lim
docs = [
{"id": "public-access-policy", "g": {"employees"}, "del": False, "s": 0.82},
{"id": "finance-plan", "g": {"finance"}, "del": False, "s": 0.99},
{"id": "old-handbook", "g": {"employees"}, "del": True, "s": 0.95},
]
eligible = [d["id"] for d in sorted(docs, key=lambda x: x["s"], reverse=True) if not d["del"] and (d["g"] & {"employees"})]
print("fresh(20,90,None):", [fresh(a, 60) for a in (20, 90, None)], "| eligible:", eligible)fresh(20,90,None): [True, False, False] | eligible: ['public-access-policy']
Durable state bounds agent side effects
Persist legal transitions with atomic expected-state claims (CAS) so terminal states (failed, canceled, complete) never reopen; follow-up work opens a new attempt ID. Separate cancel intent from confirmed sandbox exit and enforce tool scopes. Pure reads (repo_read) retry automatically; writes (sandbox_provision, create_commit, post_comment) replay only when verified receiver config guarantees idempotency with literal boolean True (is True, rejecting strings like "False" or "True").[4]
NEXT = {
"queued": {"provisioning", "canceled"}, "provisioning": {"running", "failed", "canceled"},
"running": {"blocked", "review", "failed", "canceled"}, "blocked": {"running", "review", "failed", "canceled"},
"review": {"running", "complete", "canceled"}, "failed": set(), "canceled": set(), "complete": set(),
}
def retry_mode(act: str, idemp: object = False) -> str:
if act == "repo_read":
return "automatic"
if act in {"sandbox_provision", "create_commit", "post_comment"} and idemp is True:
return "automatic-with-idempotency"
return "reconcile-or-review"
print("transitions:", [(a, b, b in NEXT[a]) for a, b in (("running", "review"), ("review", "failed"), ("complete", "running"))])
for act, flg in [("repo_read", False), ("create_commit", False), ("post_comment", True), ("create_commit", "False")]:
print(f"{act:14s} idemp={flg!r:7s} -> {retry_mode(act, flg)}")transitions: [('running', 'review', True), ('review', 'failed', False), ('complete', 'running', False)]
repo_read idemp=False -> automatic
create_commit idemp=False -> reconcile-or-review
post_comment idemp=True -> automatic-with-idempotency
create_commit idemp='False' -> reconcile-or-reviewEvaluation becomes a release boundary
Every failed or missing required check blocks launch, and postmortem cases join the regression suite.[10] Verify echoed evaluator minima against the host's REQUIRED_MINIMA, and check type(leaks) is int and leaks == 0 because Python treats False == 0 as True. For online canaries, any confirmed leak (> 0) triggers immediate "rollback" even while perf metrics are pending; missing metrics, error_rate > 0.01, or p95 > 900 return "hold"; clean windows within inclusive limits return "expand".
MINIMA = {"retrieval_recall": 0.92, "citation_faithfulness": 0.95}
def launch_failures(checks: dict[str, tuple[float, float]], leaks: object) -> list[str]:
fails = [k for k, req in MINIMA.items()
if not (r := checks.get(k)) or len(r) != 2 or not (0 <= r[0] <= 1 and 0 <= r[1] <= 1) or r[1] != req or r[0] < req]
if type(leaks) is not int or leaks != 0:
fails.append("permission_leaks")
return fails
def canary(err: float | None, p95: float | None, leaks: int | None) -> str:
if type(leaks) is not int or leaks < 0:
return "hold"
if leaks > 0:
return "rollback"
if err is None or p95 is None or not (0 <= err <= 1) or p95 < 0 or err > 0.01 or p95 > 900:
return "hold"
return "expand"
print("altered:", launch_failures({"retrieval_recall": (0.94, 0.92), "citation_faithfulness": (0.93, 0.0)}, 0))
print("bool: ", launch_failures({"retrieval_recall": (0.94, 0.92), "citation_faithfulness": (0.97, 0.95)}, False))
print("canary: ", [canary(*x) for x in [(0.004, 720, 0), (None, None, 1), (None, 720, 0), (0.0104, 780, 0)]])altered: ['citation_faithfulness']
bool: ['permission_leaks']
canary: ['expand', 'rollback', 'hold', 'hold']Test attractive shortcuts
| Shortcut | Missing condition | Stronger answer |
|---|---|---|
| "Static batching suffices" | Mixed lengths idle slots | Continuous batching schedules mid-flight; paged attention fixes KV fragmentation.[9][11] |
| "Only Slurm schedules GPUs" | Serving needs dynamic autoscaling | Kubernetes + KubeRay unifies training and inference.[12] |
| "Quantization ruins quality" | Calibrated AWQ/GPTQ preserves tasks | FP8 halves BF16 weights; validate quality and kernels on target GPUs.[13][14] |
Make failure visible on the board
Check six blind spots before stepping back: technology before goal (size the user promise first), unbounded caches (add invalidation, freshness, tenant isolation), vague monitoring (exact metrics, units, percentiles, owners), silent overload (429/503 with request IDs and traces), safety as a slogan (pre-retrieval ACLs, regressions, reversible canaries), and unbounded agent retries (durable CAS + verified idempotency). If every arrow answers "what happens when this fails?", your board is ready.