Skip to content
Skip to lesson
Back to Topics
LearnAI System Design & InterviewingAI Lab System Design Interview
HardSystem Design12 min read

AI Lab System Design Interview

Design multi-model LLM gateways, paged GPU serving fleets, ACL-enforced retrieval, and reversible canary deployments under strict tail-latency SLOs.

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:

  1. Goal: caller and success metric.
  2. Requirements: behavior plus latency, freshness, and privacy targets.
  3. Scale: , , tenants, docs, latency, retention.
  4. API: external and internal interfaces.
  5. : durable entities, indexes, tenant isolation.
  6. Architecture: smallest working .
  7. Reliability: retries, , , load shedding, failover.
  8. Security and safety: permissions, traces, abuse limits, fast reverts.
  9. : metrics, logs, traces, support lookup.
  10. Deployment: beta flags, , eval checks, .

Let the pressure choose the pattern

One dominant pressure anchors the first sketch:

PatternSignalCore movesFollow-up pressure
Model gatewaymulti-provider, keys, auth, entitlements, routing, quota buckets, tracestreaming, fallback opt-in, spend caps
Inference schedulerlatency, GPUs, overloadbounded queue, batcher, KV accountingtail latency, preemption, 429/503
Enterprise retrievaldocs, ACLs, citationsconnectors, ACL snapshots, pre-retrieval filterrevocation lag, fail closed, tombstones
Agent platformlong tasks, repo writesstate machine, sandbox, tool allowlistcancellation, retries, secret redaction
Eval and releaselaunch checks, red teamoffline suites, canary controller, rollbackslice 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-upStrong moveWeak move
"Traffic spikes 10x"rate limits, wait cap, tier fairness, 429/503unbounded queues
"Permissions change fast"ACL freshness cap, tombstones, fail-closed sourcesretrieve then filter
"Provider is down"opted-in fallback, circuit breaker, degraded noticesilent model swap
"Users cancel mid-run"durable cancel intent, cooperative stop, sandbox killUI-only stop button
"Support asks why"request ID, config version, route, retrieved IDsraw unstructured logs
"Eval passes, users complain"slice analysis, canary metrics, regression casetrust 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 (Mweights=P×bM_\text{weights} = P \times b) and linear KV cache (Mtoken=2×nlayers×nKV heads×dhead×pbytesM_\text{token} = 2 \times n_\text{layers} \times n_\text{KV heads} \times d_\text{head} \times p_\text{bytes}, summed across active lengths ∑iSi\sum_i S_i) on the board. For the full memory and bandwidth derivation, see Inference Mechanics: TTFT, TPS, and KV Cache. Keep decimal GB (10910^9) distinct from GiB (2302^{30}), and leave headroom for activations, workspaces, and block rounding.

For an 8B model (32 layers, dhead=128d_\text{head}=128) 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 (8 KV heads, 131,072 B/token) cuts KV to 4.3 GB (an architecture choice, not a runtime flag).[2][3]

HBM bar chart on a 0 to 20 GB axis for a Llama 3 8B-shaped model at batch 16 and 2048 tokens. BF16 weights sit at 16.0 GB. Multi-head attention KV cache is 17.2 GB, taller than the weights. Grouped-query attention with 8 key/value heads cuts KV to 4.3 GB.
At batch 16 and 2K tokens, MHA KV (17.2 GB) exceeds weights (16.0 GB); 8-head GQA drops KV to 4.3 GB.

Leave a decision trail

DecisionChosenRejectedReversal signal
Queue placementbefore provider callinside each adapteradapter-specific SLO
Retrieval ACLbefore rerank/generationpost-generation filternone for sensitive docs
Fallback modelexplicit opt-insilent auto-swapcustomer opt-in
Agent repo writespatch + human reviewdirect branch pushreversible 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
WindowOutput
0-9 mingoal, users, success metric, functional/non-functional bounds
9-14 minone scale calculation exposing the main bottleneck
14-28 minAPI, durable data model, smallest working request path
28-40 minoverload (429/503), ACLs, support trace, eval/canary release
40-45 mintradeoffs, 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; 429 caller quota, 503 shared saturation, grounded Retry-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

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]

Diagram showing Client, API gateway, Auth + quota, and Request queue.

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:

gateway-quota-budget.py
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:,}")
Output
tpm=6,600,000 tps=110,000 headroom=15,000 (12.0% unused)
quota: after_reserve=8,200 refund=+280 final=8,480

Queueing 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

(compute-bound, driving , skipping cached prefixes[7]) and decode (bandwidth-bound, driving and ) 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 N>1N > 1, undefined for 1 token), and goodput / (explicitly per-request vs. fleet aggregate, paired with 429/503 rates and /p99 latency).

Choose a serving lever by failure mode

LeverFixesReach for it when
KV fragmentationLong contexts exhaust contiguous KV
Idle batch slotsMixed lengths stall static batches[9]
Prefix / radix cacheRepeated prefillShared system prompts or history
Speculative decodingBandwidth-bound decodeCheap draft yields high acceptance
Chunked prefillPrefill pausing decodeLong prompts spike ITL
DisaggregationPrefill/decode contentionShared 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: needs NVLink bandwidth for all-reduces, crosses slower links with pipeline bubbles, and shards 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):

Dual quantitative comparison of unbounded queueing versus load shedding at a 0.25s TTFT limit. Left: p95 wait in an unbounded queue climbs to 0.56s at 98% load while load shedding caps accepted wait at 0.24s. Right: for a 125k tok/s cluster, caller RPM limit fails fast with 429 (0s wait), 20k tokens clear in 0.16s, 31.25k hits the 0.25s SLO cap, and 50k sheds with 503 at 0.40s.
Load shedding caps accepted wait under 0.25 s with 503; caller quota returns 429 at zero queue wait.
scheduler-capacity.py
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))
Output
20k@125k: True | 50k@125k: False
ok: True full: False low_kv: False

Permissions 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:

Diagram showing Source ingestion, ACL snapshot, Hybrid index, and Authenticated query.
acl-eligibility.py
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)
Output
fresh(20,90,None): [True, False, False] | eligible: ['public-access-policy']
Eligibility table for a user in the employees group. Finance-plan has the highest score, 0.99, but the user lacks finance access. Old-handbook scores 0.95 but is deleted. Only public-access-policy, score 0.82, reaches reranking.
High similarity never overrides missing access or tombstones; only public-access-policy reaches reranking.

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 . 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]

agent-state-and-retry.py
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)}")
Output
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-review

Evaluation 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".

release-and-canary.py
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)]])
Output
altered: ['citation_faithfulness']
bool:    ['permission_leaks']
canary:  ['expand', 'rollback', 'hold', 'hold']

Test attractive shortcuts

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.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A replica has 6B weights (2 B each), 24 layers, 4 KV heads, d_head=128, 2 B/element. Three requests retain 512, 1,536, and 2,048 tokens with no sharing. Weights (decimal GB) and KV cache (GiB)?
2.Bucket starts at 7,000. Request r7 reserves 1,200, uses 930, and webhook arrives twice. Independently from 7,000, r8 reserves 1,200 and disconnects unsettled. Available tokens?
3.Request A is under quota (18k backlog at 90k/s <=0.25s, 64/64 decode slots full, 10/10 KV free). Request B exceeds caller quota on idle GPUs. Status codes?
4.Stream starts at 60 ms; four output tokens arrive at 240, 345, 465, 480 ms. TTFT, TPOT, and max ITL?
5.Payroll ACL snapshot arrives at 0 s (granted), refreshes at 52 s (granted), and authority revokes + notifies at 60 s. Max age 30 s. Searches at 20, 50, 70 s. When may payroll reach reranking?
6.Private prefix entry for doc D4 stores tokens [13,5,21] at positions [8,9,10]. With matching tenant/model/layout, which lookup may reuse it?
7.Attempt r21 is review (legal: running, complete, canceled). W1 expects running->canceled; W2 expects review->failed. Attempt r22 is complete. Which commit, and how is later r22 work tracked?
8.Replies are lost for four transient calls with verified idempotency settings (quoted values are strings). Which requires reconciliation/review before retry?
9.Host requires recall >=0.94, faithfulness >=0.96, exact echoed minima, and integer 0 leaks. Packet format: recall (obs,min), faithfulness (obs,min), leaks. Which passes?
10.Canary expands at <=1% errors, <=900 ms p95, 0 leaks; >0 leaks rolls back. East: 26/2,500 err, 780 ms, 0 leaks. North: 24/2,400 err, 900 ms, 0 leaks. West: pending perf, 2 leaks. Proposed: expand East/North, rollback West. Fix?

10 questions remaining.

References

Interview guide

OpenAI · 2026

https://openai.com/interview-guide/

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints.

Ainslie, J., et al. · 2023 · EMNLP 2023

https://arxiv.org/abs/2305.13245

Making retries safe with idempotent APIs

Featonby, M. · 2021

https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/

Additional HTTP Status Codes

Mark Nottingham and Roy Fielding · 2012

https://www.rfc-editor.org/rfc/rfc6585.html#section-4

HTTP Semantics: 503 Service Unavailable

Roy Fielding, Mark Nottingham, and Julian Reschke · 2022

https://www.rfc-editor.org/rfc/rfc9110.html#section-15.6.4

Prompt caching

OpenAI · 2026

https://developers.openai.com/api/docs/guides/prompt-caching

DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving.

Zhong, Y., et al. · 2024 · OSDI 2024

https://arxiv.org/abs/2401.09670

Paged Attention, IFB, and Request Scheduling.

NVIDIA · 2026

https://nvidia.github.io/TensorRT-LLM/features/paged-attention-ifb-scheduler.html

NeurIPS Paper Checklist Guidelines

NeurIPS · 2026

https://neurips.cc/public/guides/PaperChecklist

Efficient Memory Management for Large Language Model Serving with PagedAttention.

Kwon, W., et al. · 2023 · SOSP 2023

https://arxiv.org/abs/2309.06180

KubeRay and Ray clusters on Kubernetes.

Ray (Anyscale) · 2026

https://docs.ray.io/en/latest/cluster/getting-started.html

AWQ: Activation-aware Weight Quantization for LLM Compression and Acceleration.

Lin, J., et al. · 2023 · MLSys 2024

https://arxiv.org/abs/2306.00978

GPTQ: Accurate Post-Training Quantization for Generative Pre-Trained Transformers

Frantar, E., et al. · 2023 · ICLR 2023

https://arxiv.org/abs/2210.17323

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.