SynfraCore
Synfracore
Start Learning
Navigation

Academies

Platform

RoadmapsLabsCertificationsInterviewPYQsAI AssistantCareer
Start Learning Free Learning Roadmaps

LLM Engineering — Advanced

Production patterns, performance, security hardening

📄
Last updated Dec 2026
Expert Content

LLM Engineering Advanced

Multi-Agent Systems with LangGraph

One-line idea: A graph-based pipeline makes retry/validation logic explicit as nodes and edges instead of burying it inside nested if/else statements — the same graph-orchestration idea covered in ai/ai-agents, applied here to a RAG pipeline specifically.

python
from langgraph.graph import StateGraph, END
from typing import TypedDict

class AgentState(TypedDict):
    query: str
    docs: list
    answer: str
    attempts: int

def retrieve(state: AgentState) -> AgentState:
    state["docs"] = vectordb.search(state["query"], top_k=5)
    return state

def generate(state: AgentState) -> AgentState:
    context = "\n".join(d.text for d in state["docs"])
    state["answer"] = llm.invoke(f"Context: {context}\nQ: {state['query']}")
    state["attempts"] = state.get("attempts", 0) + 1
    return state

def validate(state: AgentState) -> str:
    if state["attempts"] >= 3:
        return "end"
    if len(state["answer"]) < 20:
        return "retrieve"
    return "end"

graph = StateGraph(AgentState)
graph.add_node("retrieve", retrieve)
graph.add_node("generate", generate)
graph.add_edge("retrieve", "generate")
graph.add_conditional_edges("generate", validate, {"end": END, "retrieve": "retrieve"})
graph.set_entry_point("retrieve")
app = graph.compile()

result = app.invoke({"query": "What is the LUPA threshold for PDGM wound care?"})

Common mistake + fix: Looping retrieve → generate without a hard cap, trusting the validation check to eventually succeed. Fix: the attempts >= 3 check above exists for exactly this reason — a model that keeps producing a short/unsatisfying answer has no guaranteed reason to improve on attempt 4 just because it didn't on attempts 1-3; cap it and return the best-effort result.

Memory line: A graph makes retry logic a visible, testable path through named nodes — not a loop you have to trace through nested conditionals to understand.

Fine-Tuning vs RAG Decision Framework

One-line idea: RAG changes what the model knows at answer time; fine-tuning changes how the model behaves, permanently — most real systems need one or both, and picking wrong means paying for retraining when a document update would have worked, or fighting prompt length forever when a few training examples would have fixed the format.

ScenarioUse RAGUse Fine-tuning

|----------|---------|----------------|

Frequently updated knowledgeYESNo
Proprietary document Q&AYESNo
Style/tone consistencyNoYES
Domain-specific reasoningYES + FTYES
Reduce hallucinationsYESNo
Real-time dataYESNo
Reduce prompt lengthNoYES

Common mistake + fix: Trying to bake new factual knowledge into a model permanently through fine-tuning. Fix: fine-tuning is slow and expensive to update and the model can still get facts wrong even after training on them — RAG is almost always the better tool for fact injection specifically; reserve fine-tuning for consistent style, tone, or domain-specific reasoning patterns that prompting alone struggles to achieve reliably.

Observability Setup

One-line idea: Tracing records every step a request took through the pipeline — which node ran, what it returned, how long it took — so a bad answer can be traced back to the specific step that caused it, instead of just seeing the final (wrong) output with no record of how it got there.

python
from langsmith import traceable
import os

# Set LANGCHAIN_API_KEY/LANGCHAIN_PROJECT in the environment (never
# hard-code a key) before this import runs; tracing reads them automatically.
os.environ["LANGCHAIN_TRACING_V2"] = "true"

@traceable(run_type="chain")
def rag_pipeline(question: str) -> str:
    docs = retrieve(question)          # auto-traced
    prompt = build_prompt(docs, question)
    answer = llm.invoke(prompt)        # auto-traced
    return answer

Memory line: Tracing turns "the answer was wrong somewhere in there" into "the answer was wrong specifically at this step" — see ai/llmops for the fuller observability picture (spans, token/latency/cost metrics, incident response).

vLLM for Open-Source Model Serving

One-line idea: Self-hosting an open-source model through a server like vLLM trades the convenience of a managed API for control over cost, data residency, and latency — at the cost of managing the serving infrastructure yourself.

bash
# Install and serve Llama 3.1 8B with vLLM
pip install vllm
python -m vllm.entrypoints.openai.api_server   --model meta-llama/Meta-Llama-3.1-8B-Instruct   --port 8000   --max-model-len 8192   --tensor-parallel-size 1

# Now call it like OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="any")
💡 In simple words

One-line idea: Self-hosting makes sense once a specific constraint — cost at high volume, data that can't leave your infrastructure, or latency a network round-trip can't hit — outweighs the convenience of a managed API.

Try it in 2 minutes: A team processes a small number of requests per day and has no data-residency requirement. Does self-hosting an open-source model make sense for them?

Answer: Probably not — at low volume, the engineering cost of running and maintaining your own serving infrastructure (GPU provisioning, scaling, upgrades) usually outweighs any savings versus a managed API call, which has none of that operational overhead.

Common mistake + fix: Self-hosting for cost savings before measuring whether the actual request volume justifies the infrastructure overhead. Fix: estimate the all-in cost of self-hosting (compute, ops time, reliability engineering) against actual API spend at current volume before committing — the breakeven point is usually higher than it first appears.

Memory line: Self-hosting is a real option once a specific constraint demands it — not a default upgrade path from "using an API."

Rate Limiting and Budget Caps

One-line idea: A per-user rate limit and a per-user/per-day budget cap solve different problems — one protects your API quota from being exhausted by a single caller, the other protects your bill from one runaway loop or abusive user.

python
import time
from collections import defaultdict

class RateLimiter:
    def __init__(self, max_requests: int, window_s: float):
        self.max_requests = max_requests
        self.window_s = window_s
        self.calls: dict[str, list[float]] = defaultdict(list)

    def allow(self, user_id: str) -> bool:
        now = time.monotonic()
        self.calls[user_id] = [t for t in self.calls[user_id] if now - t < self.window_s]
        if len(self.calls[user_id]) >= self.max_requests:
            return False
        self.calls[user_id].append(now)
        return True

class BudgetGuard:
    def __init__(self, daily_cap_tokens: int):
        self.daily_cap_tokens = daily_cap_tokens
        self.usage: dict[str, int] = defaultdict(int)

    def check_and_record(self, user_id: str, tokens_used: int) -> bool:
        if self.usage[user_id] + tokens_used > self.daily_cap_tokens:
            return False
        self.usage[user_id] += tokens_used
        return True

Common mistake + fix: Only rate-limiting requests per minute and assuming that also caps spend. Fix: a user making a few large, expensive requests can still blow a budget while staying well under a request-count limit — track tokens/cost separately from request count.

Memory line: Rate limiting caps how often someone can call you. A budget guard caps how much any single caller can cost you — track both, since neither one substitutes for the other.

Production Checklist

A checklist works as a gate, not a suggestion — each line corresponds to a specific failure mode covered elsewhere on this page or in ai/llmops/ai/ai-agents: prompt versioning (Intermediate) catches silent prompt drift, input/output validation and PII scrubbing (Intermediate's Guardrails) catch unsafe content, fallback/retry (Intermediate) catches transient failures, and cost/latency monitoring (this page, ai/llmops) catches a regression nobody would otherwise notice until the bill or the complaints arrive.

Common mistake + fix: Treating this checklist as a one-time pre-launch exercise instead of an ongoing operational practice. Fix: re-check it whenever the prompt, model, or retrieval index changes significantly — a system that passed every item at launch can silently drift out of compliance with any one of them months later without a single code change triggering the drift (a model provider's own update, a slowly growing user base hitting rate limits differently, a document feed introducing new PII patterns).

Memory line: A production checklist is a recurring audit, not a launch-day formality — the failure modes it guards against don't go away just because the system shipped successfully once.

•[ ] Prompt versioned and tracked in git
•[ ] Input sanitised (no prompt injection)
•[ ] Output validated (schema, length, toxicity)
•[ ] Fallback for LLM errors (retry + degraded response)
•[ ] Cost alert: budget cap per user/day
•[ ] Latency monitored: TTFT + total response time
•[ ] RAGAS scores tracked weekly
•[ ] PII scrubbing before sending to LLM API
•[ ] Rate limiting per user
•[ ] Caching layer for identical queries
Share:
Join our Community
Daily tips, job alerts, interview help — join engineers learning together
→
✅Quick Check — LLM Engineering
1 / 1

What is the first step when optimizing a production system?

Up Next
🏗️
LLM Engineering — Projects
Portfolio-ready projects to demonstrate your skills
Also Worth Exploring
← Back to all LLM Engineering modules
← IntermediateRoadmap →