Home / AI Architecture

AI Architecture & Design

18 system design questions, each with an architecture diagram you can sketch on the whiteboard, linked to its full 40-minute answer.

How to read the diagrams

Applications

Support chatbot over a knowledge baseComponents: Chat widget (web · mobile); API gateway (auth · rate limits); Orchestrator (conversation flow); Input guardrails (PII · injection · abuse); Intent router (small model); Retrieval (hybrid search + rerank); Answer LLM (streams, cites sources); Output guardrails (policy · grounding); Conversation store (history · summaries); Tracing & evals (feedback · golden set); KB index (vectors · BM25 · locale); Human handoff (ticket + AI summary); Help-center CMS (webhook on publish); Ingestion (parse · chunk · headers); Embedding model (batch embed). Flow: Chat widget to API gateway; API gateway to Orchestrator; API gateway to Conversation store (history); Orchestrator to Input guardrails; Input guardrails to Intent router; Intent router to Retrieval (route); Retrieval to KB index (top 50); Retrieval to Answer LLM; Answer LLM to Output guardrails; Answer LLM to Human handoff (escalate); Orchestrator to Tracing & evals (traces); Help-center CMS to Ingestion; Ingestion to Embedding model; Embedding model to KB index (upsert).OFFLINE INGESTIONChat widgetweb · mobileAPI gatewayauth · rate limitsOrchestratorconversation flowInput guardrailsPII · injection · abuseIntent routersmall modelRetrievalhybrid search + rerankAnswer LLMstreams, cites sourcesOutput guardrailspolicy · groundingConversation storehistory · summariesTracing & evalsfeedback · golden setKB indexvectors · BM25 · localeHuman handoffticket + AI summaryHelp-center CMSwebhook on publishIngestionparse · chunk · headersEmbedding modelbatch embedhistoryroutetop 50streamed answerescalatetracesupsert

AI System DesignSenior

Support chatbot over a knowledge base

Design a customer-support chatbot that answers from a company knowledge base.

RAG over internal documentsComponents: Connectors (Confluence · Drive · Jira); Parse & clean (keep headings, tables); Chunk (by section + breadcrumbs); Embed (embedding model); Hybrid index (vectors · BM25 · ACL); Employee (chat UI); Query rewrite (standalone question); Hybrid retrieve (ACL filter · RRF); Reranker (50 → 5 chunks); Answer LLM (cites source IDs); Logs & evals (recall@k · faithfulness); Citation check (claims vs sources). Flow: Connectors to Parse & clean; Parse & clean to Chunk; Chunk to Embed; Embed to Hybrid index; Employee to Query rewrite; Query rewrite to Hybrid retrieve; Hybrid retrieve to Reranker; Reranker to Answer LLM; Answer LLM to Citation check; Hybrid retrieve to Logs & evals (traces).INGESTION · OFFLINE, INCREMENTALQUERY · ONLINEConnectorsConfluence ·Drive · JiraParse & cleankeep headings, tablesChunkby section +breadcrumbsEmbedembedding modelHybrid indexvectors · BM25 · ACLEmployeechat UIQuery rewritestandalone questionHybrid retrieveACL filter · RRFReranker50 → 5 chunksAnswer LLMcites source IDsLogs & evalsrecall@k · faithfulnessCitation checkclaims vs sourcessearchanswer + sourcestraces

RAG & Vector SearchMid

RAG over internal documents

Walk me through how you'd build a RAG system over a company's internal docs.

Real-time moderation of streaming LLM outputComponents: Audit log (every decision); Human review (samples · appeals); Policy service (per-tenant thresholds); LLM (token stream); LLM gateway (proxies the stream); Segmenter (sentence windows); Tier 1 classifiers (~5 ms per window); Decision engine (allow · redact · halt); Tier 2 LLM judge (borderline windows); User (receives safe stream). Flow: LLM to LLM gateway; LLM gateway to Segmenter; Segmenter to Tier 1 classifiers; Tier 1 classifiers to Decision engine; Tier 1 classifiers to Tier 2 LLM judge (uncertain); Tier 2 LLM judge to Decision engine (score); Policy service to Decision engine (thresholds); Decision engine to User (release); Audit log to Human review.Audit logevery decisionHuman reviewsamples · appealsPolicy serviceper-tenant thresholdsLLMtoken streamLLM gatewayproxies the streamSegmentersentence windowsTier 1 classifiers~5 ms per windowDecision engineallow · redact · haltTier 2 LLM judgeborderline windowsUserreceives safe streamuncertainscorethresholdsreleaselog decision

AI System DesignSenior

Real-time moderation of streaming LLM output

Design a content moderation service that inspects LLM outputs in real time.

Retrieval

Hybrid retrieval with rank fusionComponents: Query; BM25 (exact terms · IDs); Vector ANN (semantic similarity); RRF fusion (Σ 1 / (60 + rank)); Cross-encoder (rerank top 50); Top 5 chunks (sent to the LLM). Flow: Query to BM25; Query to Vector ANN; BM25 to RRF fusion (top 50); Vector ANN to RRF fusion (top 50); RRF fusion to Cross-encoder; Cross-encoder to Top 5 chunks.QueryBM25exact terms · IDsVector ANNsemantic similarityRRF fusionΣ 1 / (60 + rank)Cross-encoderrerank top 50Top 5 chunkssent to the LLMtop 50top 50

RAG & Vector SearchMid

Hybrid retrieval with rank fusion

Why use hybrid search instead of only vector search?

Permission-aware retrievalComponents: Identity provider (user → groups); Employee; RAG API (resolve caller groups); Filtered search (acl ∩ user groups); Permission re-check (sensitive docs only); LLM (permitted chunks only); Index (chunks + ACL metadata); Audit log (who retrieved what); Source systems (SharePoint · Jira); ACL sync (events + nightly reconcile). Flow: Employee to RAG API; RAG API to Identity provider (groups); RAG API to Filtered search; Filtered search to Index; Filtered search to Permission re-check; Permission re-check to LLM; Permission re-check to Audit log (log); Source systems to ACL sync; ACL sync to Index (update ACLs).ACL SYNCIdentity provideruser → groupsEmployeeRAG APIresolve caller groupsFiltered searchacl ∩ user groupsPermission re-checksensitive docs onlyLLMpermitted chunks onlyIndexchunks + ACL metadataAudit logwho retrieved whatSource systemsSharePoint · JiraACL syncevents + nightlyreconcilegroupslogupdate ACLs

RAG & Vector SearchSenior

Permission-aware retrieval

How do you enforce document permissions in RAG?

Zero-downtime embedding model migrationComponents: Index v1 (old embedding model); Queries; Doc updates; Dual-write (during migration); Query router (flag: % to v2); Shadow compare (eval set + feedback); Backfill job (batched, checkpointed); Index v2 (new embedding model). Flow: Doc updates to Dual-write; Dual-write to Index v1; Dual-write to Index v2; Backfill job to Index v2 (re-embed corpus); Queries to Query router; Query router to Index v1; Query router to Index v2; Query router to Shadow compare (mirror).Index v1old embedding modelQueriesDoc updatesDual-writeduring migrationQuery routerflag: % to v2Shadow compareeval set + feedbackBackfill jobbatched, checkpointedIndex v2new embedding modelre-embed corpusmirror

RAG & Vector SearchSenior

Zero-downtime embedding model migration

Your embedding provider releases a better model. How do you migrate?

Semantic cache with safeguardsComponents: Semantic cache (answers · TTL); Content updates (invalidate entries); User; Rewrite (standalone question); Embed query; Cache lookup (scoped: tenant · locale); Equivalence check (threshold + verifier); LLM (on cache miss). Flow: User to Rewrite; Rewrite to Embed query; Embed query to Cache lookup; Cache lookup to Semantic cache (search); Cache lookup to Equivalence check; Cache lookup to LLM (miss); Equivalence check to LLM (not equal); Content updates to Semantic cache.Semantic cacheanswers · TTLContent updatesinvalidate entriesUserRewritestandalone questionEmbed queryCache lookupscoped: tenant · localeEquivalence checkthreshold + verifierLLMon cache misssearchhit → cached answermissnot equalfresh answerstore

AI System DesignMid

Semantic cache with safeguards

Explain semantic caching and its risks.

Serving & reliability

Latency breakdown before and after optimizationBefore · sequential, no streaming: Network + queue 0.2s, Query rewrite (large) 0.9s, Retrieval 0.4s, Prefill (TTFT) 1.2s, Decode 520 tokens 5.2s, Verification 0.3s; first visible text at 8.2s; total 8.2s. After · small rewrite model, 4 chunks, short answers, streaming: Network + queue 0.2s, Query rewrite (small) 0.2s, Retrieval 0.4s, Prefill (TTFT) 0.6s, Decode ~180 tokens 1.8s, Verification 0.3s; first visible text at 1.4s; total 3.5s.Before · sequential, no streamingtotal 8.2 sNetwork + queue0.2 sQuery rewrite (large)0.9 sRetrieval0.4 sPrefill (TTFT)1.2 sDecode 520 tokens5.2 sVerification0.3 sfirst text 8.2 s0s1s2s3s4s5s6s7s8sAfter · small rewrite model, 4 chunks, short answers, streamingtotal 3.5 sNetwork + queue0.2 sQuery rewrite (small)0.2 sRetrieval0.4 sPrefill (TTFT)0.6 sDecode ~180 tokens1.8 sVerification0.3 sfirst text 1.4 s0s1s2s3s4s5s6s7s8s

AI System DesignMid

Latency breakdown before and after optimization

How would you reduce the latency of an LLM feature that currently takes 8 seconds?

Model router with a verification cascadeComponents: Fallback provider (used during outages); Monitor (quality · cost · drift); Request; Router (classifier on embedding); Small model (~70% of traffic); Verifier / tests (cascade check); Response; Large model (hard requests). Flow: Request to Router; Router to Small model (easy); Router to Large model (hard); Small model to Verifier / tests; Verifier / tests to Response (pass); Verifier / tests to Large model (fail → escalate); Router to Fallback provider (provider down); Response to Monitor (log outcome).Fallback providerused during outagesMonitorquality · cost · driftRequestRouterclassifier on embeddingSmall model~70% of trafficVerifier / testscascade checkResponseLarge modelhard requestseasyhardpassfail → escalateanswerprovider downlog outcome

AI System DesignSenior

Model router with a verification cascade

How would you design a model router?

Central, token-aware rate limitingComponents: Tenant quotas (daily token budgets); Batch API (offline, discounted); Services (chat · agents · jobs); Token limiter (Redis token bucket); Priority queue (interactive first); LLM client (backoff + jitter); LLM provider (RPM · TPM limits); Fallback model (other region / provider). Flow: Services to Token limiter; Tenant quotas to Token limiter; Token limiter to Priority queue; Priority queue to LLM client; Priority queue to Batch API (batch work); LLM client to LLM provider; LLM provider to LLM client (429 + Retry-After); LLM client to Fallback model (overloaded).Tenant quotasdaily token budgetsBatch APIoffline, discountedServiceschat · agents · jobsToken limiterRedis token bucketPriority queueinteractive firstLLM clientbackoff + jitterLLM providerRPM · TPM limitsFallback modelother region / providerbatch work429 + Retry-Afteroverloaded

Coding with AI APIsSenior

Central, token-aware rate limiting

How do you handle rate limits from an LLM provider at scale?

Validate-and-repair loop for structured outputComponents: Input (ticket text); Prompt + schema (fields, enums, nulls); LLM (structured output mode); Schema validation (Pydantic / Zod); Semantic checks (IDs exist, ranges ok); Repair prompt (adds validation error); Downstream system (DB · queue · UI); Fallback (after N tries → human). Flow: Input to Prompt + schema; Prompt + schema to LLM; LLM to Schema validation; Schema validation to Semantic checks; Semantic checks to Downstream system (valid); Schema validation to Repair prompt (invalid); Repair prompt to LLM (retry); Schema validation to Fallback (N failures).Inputticket textPrompt + schemafields, enums, nullsLLMstructured output modeSchema validationPydantic / ZodSemantic checksIDs exist, ranges okRepair promptadds validation errorDownstream systemDB · queue · UIFallbackafter N tries → humanvalidinvalidretryN failures

AI System DesignJunior

Validate-and-repair loop for structured output

How do you get reliable JSON out of an LLM?

Streaming LLM responses to the browserComponents: Secrets manager (provider API key); Browser (fetch + ReadableStream); Reverse proxy (buffering off); Your backend (auth · quotas · relay); LLM provider (streaming API); Usage log (tokens per user). Flow: Browser to Reverse proxy; Reverse proxy to Browser; Reverse proxy to Your backend; Your backend to Reverse proxy; Your backend to LLM provider (stream request); LLM provider to Your backend (SSE events); Secrets manager to Your backend (key); Your backend to Usage log (usage).Secrets managerprovider API keyBrowserfetch + ReadableStreamReverse proxybuffering offYour backendauth · quotas · relayLLM providerstreaming APIUsage logtokens per userstream requestSSE eventskeyusagePOST /chat →← SSE: delta · done · errorClient abort → cancel upstream

Coding with AI APIsMid

Streaming LLM responses to the browser

How would you stream an LLM response to a web client?

LLM observability pipeline with privacy tiersComponents: Metrics (long retention); Dashboards & alerts (latency · cost · errors); LLM app (trace SDK · trace IDs); Redaction (PII · secrets); Collector (OpenTelemetry); Sanitized traces (medium retention); Debugging (follow one request); Full transcripts (restricted · sampled); Eval cases (built from failures). Flow: LLM app to Redaction; Redaction to Collector; Collector to Sanitized traces; Collector to Metrics; Collector to Full transcripts (sampled); Metrics to Dashboards & alerts; Sanitized traces to Debugging; Full transcripts to Eval cases.Metricslong retentionDashboards & alertslatency · cost · errorsLLM apptrace SDK · trace IDsRedactionPII · secretsCollectorOpenTelemetrySanitized tracesmedium retentionDebuggingfollow one requestFull transcriptsrestricted · sampledEval casesbuilt from failuressampled

AI System DesignMid

LLM observability pipeline with privacy tiers

What would you log for an LLM request, and what would you avoid logging?

Model rollout pipeline with gatesComponents: Candidate model (pinned version); Golden sets (per feature + safety); Offline eval (paired, per category); Shadow traffic (outputs not shown); Canary (1–5% of users); Ramp (25% → 50% → 100%); Online metrics (success · feedback · cost); Feature flag (instant rollback). Flow: Golden sets to Offline eval; Candidate model to Offline eval; Offline eval to Shadow traffic (gate); Shadow traffic to Canary (gate); Canary to Ramp (gate); Online metrics to Canary (monitor); Feature flag to Canary; Ramp to Feature flag (rollback).Candidate modelpinned versionGolden setsper feature + safetyOffline evalpaired, per categoryShadow trafficoutputs not shownCanary1–5% of usersRamp25% → 50% → 100%Online metricssuccess ·feedback · costFeature flaginstant rollbackgategategatemonitorrollback

AI System DesignMid

Model rollout pipeline with gates

How would you evaluate a new model before switching production traffic to it?

Agents & safety

Agent loop with safeguardsComponents: Budgets (max steps · tokens); Final answer; User confirmation (destructive actions); User task; LLM call (tools + history); stop_reason? (tool_use or end_turn); Validate + authorize (schema · permissions); Execute tool (timeout · idempotency); Append results (truncated · errors too). Flow: User task to LLM call; LLM call to stop_reason?; stop_reason? to Final answer (end_turn); stop_reason? to Validate + authorize; Validate + authorize to Execute tool; Validate + authorize to User confirmation (destructive); User confirmation to Execute tool (approved); Execute tool to Append results; Append results to LLM call (next step); Budgets to LLM call (check).Budgetsmax steps · tokensFinal answerUser confirmationdestructive actionsUser taskLLM calltools + historystop_reason?tool_use or end_turnValidate + authorizeschema · permissionsExecute tooltimeout · idempotencyAppend resultstruncated · errors tooend_turndestructiveapprovednext stepcheck

Coding with AI APIsMid

Agent loop with safeguards

Implement an agent loop. What safeguards do you add?

MCP architectureComponents: LLM (emits tool calls); Host runtime (approvals · routing); User (approves writes); MCP client; MCP client; MCP client; GitHub server (local · stdio); Database server (local · stdio); Ticketing server (remote · HTTP + OAuth); GitHub API; Postgres; Ticketing SaaS. Flow: LLM to Host runtime; User to Host runtime (approve); Host runtime to MCP client; Host runtime to MCP client; Host runtime to MCP client; MCP client to GitHub server (JSON-RPC); MCP client to Database server (JSON-RPC); MCP client to Ticketing server (JSON-RPC); GitHub server to GitHub API; Database server to Postgres; Ticketing server to Ticketing SaaS.HOST APPLICATIONLLMemits tool callsHost runtimeapprovals · routingUserapproves writesMCP clientMCP clientMCP clientGitHub serverlocal · stdioDatabase serverlocal · stdioTicketing serverremote · HTTP + OAuthGitHub APIPostgresTicketing SaaSapproveJSON-RPCJSON-RPCJSON-RPC

Coding with AI APIsJunior

MCP architecture

What is MCP?

Defence in depth against prompt injectionComponents: Untrusted content (web · email · files); Injection classifier (one signal, not a wall); Quarantined LLM (no tools, no secrets); User; Privileged agent (plans, calls tools); Tool gateway (authz · least privilege); Tools & actions (read · send · pay); Output filter (blocks exfiltration links); Human confirmation (shows the exact action). Flow: Untrusted content to Injection classifier; Injection classifier to Quarantined LLM; Quarantined LLM to Privileged agent (structured data only); User to Privileged agent (request); Privileged agent to Tool gateway; Tool gateway to Tools & actions; Tool gateway to Human confirmation (risky); Human confirmation to Tools & actions (approved); Privileged agent to Output filter; Output filter to User (response).Untrusted contentweb · email · filesInjection classifierone signal, not a wallQuarantined LLMno tools, no secretsUserPrivileged agentplans, calls toolsTool gatewayauthz · least privilegeTools & actionsread · send · payOutput filterblocksexfiltration linksHuman confirmationshows the exact actionstructured data onlyrequestriskyapprovedresponse

AI System DesignMid

Defence in depth against prompt injection

What is prompt injection and how do you defend against it?

The lethal trifectaComponents: Private data (email · files · secrets); Untrusted content (web · inbox · issues); AI agent (tools + model); Outbound channel (email · HTTP · image URLs); Attacker (controls content + server). Flow: Private data to AI agent (reads); Untrusted content to AI agent (reads); AI agent to Outbound channel (sends); Attacker to Untrusted content (plants instructions); Outbound channel to Attacker (data leaks).Private dataemail · files · secretsUntrusted contentweb · inbox · issuesAI agenttools + modelOutbound channelemail · HTTP· image URLsAttackercontrolscontent + serverreadsreadssendsplants instructionsdata leaksBreak the trifecta by removing one leg:• isolate untrusted-content tasks from private data• privileged agents read only vetted sources• no open egress; approve every send

AI System DesignSenior

The lethal trifecta

What is the 'lethal trifecta' for AI agents?