Reference architecture of an LLM application

In one sentence

A production LLM app is layers around the model: client → API & auth → orchestration → context (retrieval, memory, tools) → model gateway → models, wrapped in guardrails, evals, observability and cost control.

Analogy: A restaurant: the chef (model) matters, but so do the host checking reservations, the ticket system, the pantry, the expediter inspecting every plate and the books. Great chefs still fail in badly run kitchens.

Solid: the online request path. Dashed: offline loops that keep the index fresh and turn traces into evals and training data.

How it works

  • It is a compound AI system: retrieval, tools, checks and routing drive quality, not the model alone.
  • The API layer derives identity and tenant from the token, never from the prompt, and enforces quotas.
  • A model gateway handles routing, caching, fallbacks and cost attribution, adding only single-digit ms.
  • Availability multiplies in series: a 99.9% app on a 99.5% model API is ≈ 99.4% without a fallback.
  • Offline paths keep the index fresh and turn traces and feedback into evals and fine-tuning data: the data flywheel.

Check yourself

Answer to mark it learned; your answers aren't scored.

Five product teams each call model providers directly with their own API keys. Finance can't split the LLM bill by team, and one provider outage took down all five features. Which layer do you introduce first?

Go deeper

Full explanation

A production LLM app is a compound AI system (Berkeley BAIR, Feb 2024): quality comes from the system around the model (retrieval, tools, checks, routing), not from the model alone. Most designs share the same layers along the request path:

  1. Experience: chat or embedded UI with Streaming responses (SSE), Citations & grounding and Human-in-the-loop & approvals.
  2. API & auth: identity, tenant, quotas (Rate limiting). The tenant comes from the token, never from the prompt.
  3. Orchestration: a fixed workflow or an agent (Agents vs workflows), with Durable execution for agents so long tasks survive crashes.
  4. Context layer: RAG (Retrieval-Augmented Generation), Agent memory and tools exposed via Model Context Protocol (MCP), assembled by Context engineering.
  5. Model access: an LLM gateway with Model routing & cascades, Caching layers in an AI system, fallbacks (Resilience: multi-provider failover & degradation) and cost attribution.
  6. Models: provider APIs or self-hosted (API vs self-hosting).

Cross-cutting: Guardrails: input, output, action on input, output and actions; Identity & authorization for agents on every tool call; LLM observability & tracing traces; online evals; budgets (AI cost governance (FinOps for AI)).

Offline paths: ingestion and Index freshness & lifecycle keep retrieval fresh; traces and feedback become Golden datasets & test sets, evals and fine-tuning data: the The data flywheel.

Code One request through every layer (FastAPI sketch)
pythonOne request through every layer (FastAPI sketch)
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse

app = FastAPI()
PROMPT_VERSION = "support-v12"

@app.post("/chat")
async def chat(req: Request):
    user = authenticate(req)                         # API & auth: tenant from the token
    body = await req.json()
    enforce_quota(user.tenant, body["message"])      # rate limits + budgets
    check_input(body["message"])                     # guardrail: injection, PII

    with tracer.start_as_current_span("chat") as span:
        span.set_attribute("prompt.version", PROMPT_VERSION)
        chunks = await retrieve(body["message"], acl=user.groups)  # permission-aware RAG
        memory = await recall(user.id, body["message"])
        prompt = build_prompt(PROMPT_VERSION, memory, chunks, body["message"])  # static first

        stream = gateway.stream(                     # model access layer
            model="tier:default",                    # gateway picks model + fallbacks
            messages=prompt,
            tools=mcp_tools_for(user),               # only tools this user may use
            metadata={"tenant": user.tenant, "prompt_version": PROMPT_VERSION},
        )
        return StreamingResponse(check_output(stream, sources=chunks))  # cite + filter
Real example

An HR assistant for a 20,000-employee company. A question arrives with an SSO token; the API layer derives the employee's country and role and checks the team quota. An input guardrail masks an ID number. A 3-step workflow (no agent needed) retrieves 50 chunks filtered by country and role, reranks to 5, and the gateway sends them to a mid-size model with a cached 3k-token system prompt. The answer streams with citations at ~1 s TTFT. Every trace carries the prompt version; thumbs-down answers go to weekly error analysis and become new golden-set cases.

Trade-offs +3 · −3

+ You gain

  • Shared map for design reviews and interviews: you can point at the layer where a problem lives.
  • Layers swap independently (new model, new vector DB) behind stable interfaces.
  • Auth, cost, logging and safety are enforced once, not re-built in every feature.

− You pay

  • Overbuilt for a prototype: a prompt, one model call and an eval set may be all you need.
  • Every layer adds latency and a failure point; serial availabilities multiply.
  • A central platform can over-standardize and slow down product teams.

Use it when

As the default skeleton for any production LLM feature or system-design answer: walk the request path, then the cross-cutting concerns, then the offline loops.

Avoid it when

Don't build every layer on day one. Add a layer when a real need appears: tenants, scale, cost, risk or a second team.

Numbers to know 4
  • Databricks data cited by BAIR (2024): 60% of LLM apps used some form of RAG, 30% used multi-step chains.
  • Serial availability multiplies: a 99.9% app on a 99.5% model API is ≈ 99.4% without a fallback.
  • Rule of thumb: the model call dominates latency and cost; a gateway should add only single-digit ms.
  • Anthropic (2025): agents use ~4× the tokens of a chat interaction; multi-agent systems ~15×.
Common pitfalls 4
  • Enforcing tenant or permissions in the prompt instead of in code and retrieval filters.
  • Every service calling providers directly: no single place for keys, quotas, fallbacks or cost per team.
  • Choosing an agent where a fixed workflow would do: more tokens, less predictability.
  • No offline loop: without traces and a golden set, every model or prompt change is a guess.
Interview questions 3

Answer out loud first, then reveal.

Walk me through the architecture of a production LLM application.Show answer

I follow the request path. The client streams tokens and shows citations. The API layer authenticates and derives tenant and quotas. An orchestrator, a workflow by default and an agent only when the path can't be fixed, keeps durable state. The context layer does permission-aware retrieval, memory and tools over MCP. A gateway handles routing, caching and fallbacks across models. Around it: guardrails, per-tool authorization, tracing, online evals and budgets. Offline, ingestion keeps the index fresh and traces feed evals and fine-tuning. Then I go deep where the risk is, usually retrieval quality or cost.

What is a compound AI system, and why does it matter to an architect?Show answer

It's a system where quality comes from several interacting components, such as retrievers, multiple model calls, tools and verifiers, rather than from one model. BAIR made the case in 2024 with examples like AlphaCode 2, which generates up to a million candidate solutions and filters them. For me it changes where I invest: the model is a swappable part, while retrieval, evals and routing are where my team builds lasting advantage. The cost is more failure points and harder debugging, so per-step tracing is mandatory.

Where do you enforce security in this architecture?Show answer

In deterministic code at the boundaries, never in the prompt. Identity and tenant at the API layer, from the token. Permission filters inside retrieval. Per-tool authorization with the user's scoped credentials. Output checks before rendering, especially links and markdown images. Human approval for irreversible actions. Guardrail classifiers reduce risk, but because prompt injection has no complete fix, a hijacked model must still be unable to do damage.