Guide / AI engineering Fundamentals
21. LLMOps — gateways, caching, cost, latency, serving, fine-tuning
21.1 LLM gateway#
A central service between your apps and model providers. Responsibilities: one API across providers (OpenAI, Anthropic, Google, self-hosted), API key management, per-team quotas and budgets, rate limiting, retries and provider fallback (on 429/5xx or timeout, retry another region/model), model routing, caching, PII redaction, logging/tracing, cost attribution per team/feature. Examples: LiteLLM, Portkey, Kong/Envoy AI gateways, cloud-provider gateways.
21.2 Caching for LLM apps#
| Layer | What | Notes |
|---|---|---|
| Provider prompt caching | Reused KV cache for a repeated prefix | Large discount on cached input tokens; structure prompts stable-first |
| Exact response cache | Hash(model + prompt + params) → response | Safe; low hit rate for free-text input |
| Semantic cache | Embed query; if a past query is within a similarity threshold, return its answer | Higher hit rate; risk of wrong answers for similar-looking but different questions (“cancel my order” vs “don’t cancel my order”); scope per user/tenant; use only for non-personalized FAQs |
| Embedding cache | Text hash → vector | Avoid re-embedding unchanged chunks and repeated queries |
| Retrieval cache | Query → retrieved chunk IDs | Invalidate on re-index |
| Tool result cache | API responses (catalogue, prices) with TTL | Standard caching rules from Part 1 |
21.3 Cost optimisation#
Cost ≈ (input tokens × input price + output tokens × output price) × calls. Levers: smaller model or routing/cascades, shorter prompts and fewer retrieved chunks, prompt caching, cap output length, batch APIs for offline work (often ~50% cheaper), fewer agent steps, semantic caching, distill to a fine-tuned small model for high-volume narrow tasks, self-host at very high steady volume. Always report cost per successful task, not per call.
21.4 Latency optimisation#
Stream tokens to the user (perceived latency = TTFT); parallelize retrieval and independent tool calls; use smaller/faster models for intermediate steps (routing, query rewriting); keep prompts short and cache prefixes; reduce output length; speculative/prefetch work (start retrieval while the user is still typing or speaking); keep connections warm; colocate services and model region. Break a latency budget down by stage in interviews: e.g. 5 s = 300 ms query rewrite + 200 ms retrieval + 150 ms rerank + 800 ms TTFT + 3 s generation + overhead.
21.5 Self-hosted model serving#
- Engines: vLLM (PagedAttention for KV-cache memory, continuous batching), TGI, SGLang, TensorRT-LLM, llama.cpp/Ollama for local.
- Quantization: FP16/BF16 → INT8 → INT4 (GPTQ, AWQ, GGUF): ~2–4× less memory, some quality loss; evaluate on your tasks.
- GPU sizing: weights ≈ parameters × bytes per param (a 70B model in FP16 ≈ 140 GB → multiple GPUs; INT4 ≈ 35–40 GB), plus KV cache per concurrent request.
- Scaling: autoscale on queue depth/GPU utilization (not CPU), cold starts are slow (loading weights), tensor parallelism across GPUs for big models, separate prefill and decode pools at large scale.
- Speculative decoding: a small draft model proposes tokens, the big model verifies several at once → faster decode.
- When to self-host: data residency/privacy, very high steady volume, need for custom fine-tunes, or latency control. Otherwise APIs are cheaper in engineering time.
21.6 Fine-tuning and model adaptation#
| Technique | What | When |
|---|---|---|
| Prompting + few-shot | No training | Always try first |
| RAG | Add knowledge at query time | Facts, changing data, citations |
| SFT (supervised fine-tuning) | Train on input→ideal output pairs | Consistent format/style, domain jargon, narrow classification/extraction, shorter prompts |
| LoRA / QLoRA (PEFT) | Train small adapter matrices instead of all weights; QLoRA on a 4-bit base | Cheap fine-tuning on one GPU; swap adapters per tenant/task |
| Preference tuning (RLHF, DPO) | Learn from chosen-vs-rejected pairs | Tone, helpfulness, safety preferences |
| RL with verifiable rewards | Reward from checks (tests pass, answer correct) | Reasoning, code, agents (advanced) |
| Distillation | Train a small model on a big model’s outputs | Cut cost/latency for a high-volume task |
| Embedding / reranker fine-tuning | Train on (query, relevant doc) pairs | Retrieval quality in a specialised domain |
Risks: catastrophic forgetting, overfitting to small data, data quality (garbage in), cost of maintaining the pipeline and re-tuning on new base models, and needing evals to prove the gain. Typical data needs: hundreds to a few thousand high-quality examples for SFT/LoRA on a narrow task.
21.7 Observability for AI systems#
Trace each request as a tree: user request → retrieval spans → LLM spans (model, prompt version, tokens in/out, latency, cost) → tool spans → guardrail checks. OpenTelemetry has GenAI semantic conventions for this; tools like Langfuse, LangSmith, Arize Phoenix, Helicone, Datadog LLM Observability visualize it. Dashboards: latency percentiles per stage, error/refusal rate, token usage and cost per feature, eval scores over time, user feedback, drift in input topics.
21.8 Data pipelines for AI#
Ingestion connectors → parsing/OCR → PII scrubbing → chunking → embedding (batch, rate-limited, retried) → index; plus pipelines for eval datasets, fine-tuning datasets (logged interactions → filtered → labelled), and feedback loops. Orchestrate with Airflow/Dagster/Prefect or Temporal; make every stage idempotent and versioned (doc version, embedding model version, chunking config version).