Detailed content
🗺️ The scale map
In a prototype, the app calls the model directly. At scale, that straight line becomes a problem: each team keeps its own API key, no one knows how much each product spends, a provider outage takes everything down, and switching models means changing dozens of services. The architectural answer is the same one engineering has used for databases and payments: put layers in between, each with a clear responsibility.
Two terms guide every decision in this module. p95 latency is the response time under which 95% of calls fall—the average hides the users who waited too long; p95 doesn’t. Throughput is how much work the system delivers per unit of time (calls or tokens per second). Scaling means increasing throughput without letting p95 or cost per call exceed the agreed limit.
What it is
Large-scale AI architecture is the set of layers between apps and models: a gateway that identifies, limits, and logs; a router that picks the right model; inference servers or APIs; caches; and observability that measures latency, errors, and cost per customer.
| Layer | Responsibility | Common tools |
|---|---|---|
| Gateway | Authenticate, apply quotas, mask personal data, and log calls. | LiteLLM Proxy, API gateways (Kong, Envoy) with AI plugins. |
| Router | Choose the model by task, cost, and availability; provide fallback. | Gateway rules, lightweight classifier, custom code. |
| Inference | Run the model with the best use of the GPU. | vLLM, SGLang, TGI, Ollama/llama.cpp, managed APIs. |
| Cache | Avoid paying twice for the same work. | Provider prompt cache, Redis, vector database. |
| Observability | Measure latency, errors, tokens, and cost per customer and resource. | OpenTelemetry, Langfuse, Prometheus, and Grafana. |
Why learn
Without the map, every scaling problem becomes a separate fire: one team adds a cache, another adds retries, a third switches models. With the map, you decide which layer should solve each problem once for the whole company—and you can switch a model without touching any app.
Key concepts
🔀 Model routing
Sending every call to the most powerful model is the fastest way to blow your budget. Much of the traffic in a real product is simple: classify a ticket, extract three fields, rewrite a sentence. A small model can do that faster and more cheaply. The model router decides, call by call, which model handles the request—and what to do if it fails.
There are three strategies, which are often combined. By rule: the route type determines the model (summaries go to the small model, legal analysis to the powerful one). By classifier: a lightweight model estimates the difficulty first. Cascade: the small model tries first; a validator checks the format and confidence; if it doesn’t pass, the call moves up to the powerful model. Fallback is the alternative route when the chosen model is down, slow, or out of quota.
What it is
Model routing is the layer that chooses, for each call, the lowest-cost model capable of meeting the required quality, and redirects the call to another model or provider when the first one fails.
Goal: set up a local gateway with two models, fallback, and cache (LiteLLM Proxy).
# config.yaml — install with: pip install 'litellm[proxy]'
# run with: litellm --config config.yaml --port 4000
model_list:
- model_name: rapido # name the apps use
litellm_params:
model: ollama/qwen2.5:7b # local and free (ollama pull qwen2.5:7b)
api_base: http://localhost:11434
- model_name: forte
litellm_params:
model: anthropic/claude-sonnet-5-5 # or another provider: change the prefix and the key
api_key: os.environ/ANTHROPIC_API_KEY
router_settings:
num_retries: 2 # retry transient errors
timeout: 30 # seconds per call
fallbacks: [{"rapido": ["forte"]}] # if "rapido" fails, use "forte"
litellm_settings:
cache: true
cache_params:
type: redis # requires Redis on localhost:6379
host: localhost
port: 6379
ttl: 3600 # seconds; adjust based on how quickly the response becomes stale
# Test (in another terminal):
# curl http://localhost:4000/v1/chat/completions -H "Content-Type: application/json" \
# -d '{"model":"rapido","messages":[{"role":"user","content":"Classify: I want to cancel"}]}'
How to check: run the curl twice with the same body; the second response should come back much faster (cache). Then stop Ollama and try again: the call to "rapido" should be handled by "forte" (fallback)—if you don’t have a paid key, the error should mention the "forte" model, which proves the fallback was attempted. LiteLLM syntax changes between versions; check the documentation for the installed version.
💡 Tip
Give models functional names ("rapido," "forte," "visao"), not product names. That way, when a new model comes out, you change one line in the gateway and no app notices—and you can run A/B tests by sending some of the traffic from "forte" to the candidate.
Why learn
Routing is the cost lever with the biggest impact and the least risk: you don’t change the product; you just stop paying frontier-model prices for simple tasks. And fallback turns a provider outage—which currently takes your product down—into a temporary cost increase.
Key concepts
⚡ Inference and batching
Inference means running an already-trained model to generate a response. For a language model, it has two phases: prefill, which reads the entire prompt at once, and decode, which generates one token at a time. Prefill determines TTFT (time to first token, how long the user waits to see the first word); decode determines the speed in tokens per second after that.
Generating one token at a time leaves the GPU underused when it serves only one user. That’s why servers group requests into batches (batching). The advance that changed the economics of self-hosting was continuous batching: instead of waiting for the entire batch to finish, each freed slot gets a new request in the next step. Along with it comes management of the KV cache —the memory where the model stores what it has already read from each conversation—which is known as PagedAttention in vLLM.
What it is
It’s the engineering of serving models: grouping requests, managing context memory, choosing quantization and hardware, and deciding between a managed API and your own server, while always measuring TTFT, tokens per second, and cost per million tokens.
| Option | When it makes sense | What you take on operating |
|---|---|---|
| Managed API | Variable traffic, frontier models, small team. | Almost nothing: keys, quotas, contract, and data sent. |
| vLLM / SGLang / TGI | High, steady traffic with an open model; data that cannot leave your environment. | GPUs, autoscaling, updates, monitoring, on-call support. |
| Ollama / llama.cpp | Development, edge, low-volume internal use. | One machine; few simultaneous users. |
💡 Tip
Compare options by cost per million tokens with your real traffic, not by the GPU’s hourly price. A cheap GPU sitting idle at night may cost more than the API; a GPU running at full capacity all day with continuous batching may cost less. Measure a week of traffic before deciding.
Why learn
The “API or your own server” decision is one of the most expensive mistakes to make in AI. Understanding prefill, decode, batching, and KV cache helps you critically assess a vendor benchmark and calculate the right costs—and understand why long prompts make everything more expensive and slower.
Key concepts
🧠 Prompt cache and semantic cache
There are two different caches, and confusing them leads to the wrong decision. The prompt cache is provided by inference providers and servers: when the beginning of the prompt repeats (system instructions, a long manual, tool definitions), processing of that prefix is reused and billed at a lower rate. It doesn’t change the answer—it only speeds up prefill and reduces cost. It works when the fixed part comes before before the variable part.
O semantic cache is yours: you turn the question into an embedding (a vector of numbers that represents its meaning) and search for earlier questions with similar meanings. If the cosine similarity exceeds a threshold, it returns the saved answer without calling the model. It saves the entire call—and that also means it can return the wrong answer if the threshold is too loose or if the answer depends on who’s asking.
What it is
Prompt caching reuses the processing of a repeated prefix while keeping the answer new; semantic caching reuses the full answer to a similar question, based on embedding similarity and a calibrated threshold.
Try this: a minimal, local, free semantic cache for calibrating the threshold.
"""cache_semantico.py — meaning-based cache with local Ollama.
Before you start: ollama pull nomic-embed-text && ollama pull llama3.2
Run: python3 cache_semantico.py"""
import json, math, time, urllib.request
OLLAMA = "http://localhost:11434"
LIMIAR = 0.90 # calibrate with your data: high = few matches; low = wrong answers
cache = [] # list of (vector, question, answer). In production: vector database, separated by customer.
def chamar(rota, corpo):
req = urllib.request.Request(OLLAMA + rota, data=json.dumps(corpo).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=120) as r:
return json.loads(r.read())
def vetor(texto):
return chamar("/api/embed", {"model": "nomic-embed-text", "input": texto})["embeddings"][0]
def cosseno(a, b):
num = sum(x * y for x, y in zip(a, b))
return num / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
def perguntar(pergunta):
t0 = time.time()
v = vetor(pergunta)
sim, melhor = -1.0, None
for item in cache:
s = cosseno(v, item[0])
if s > sim:
sim, melhor = s, item
if melhor and sim >= LIMIAR:
return f"CACHE sim={sim:.3f} {time.time()-t0:.2f}s (igual a: {melhor[1]!r})", melhor[2]
resp = chamar("/api/generate", {"model": "llama3.2", "prompt": pergunta, "stream": False})["response"]
cache.append((v, pergunta, resp))
return f"MODELO melhor_sim={sim:.3f} {time.time()-t0:.2f}s", resp
for p in ["What’s the deadline for exchanging a product?",
"How many days do I have to exchange a product?",
"What’s the delivery time to the Northeast?",
"How do I get a second copy of the payment slip?"]:
origem, resp = perguntar(p)
print(f"{origem}\n {p}\n -> {resp[:90]!r}\n")
How to check: The 1st question returns "MODEL" and takes time; the 2nd (same meaning, different words) should return "CACHE" in a fraction of a second. The 3rd is the trap: "delivery time" sounds like "exchange time." Look at the best_sim printed value and adjust LIMIAR until the 2nd one gets a match and the 3rd doesn’t. This number applies to this embedding model and this type of question—change either one and recalibrate.
✓ Semantic caching works well for
- ✓Frequently asked questions with the same answer for everyone (policies, hours, how-to instructions).
- ✓Content that changes little, with a defined expiration time.
- ✓Cache separated by customer (tenant) and by prompt version.
✗ Don’t use semantic caching for
- ✗Answers that depend on a person’s data (balance, order, medical record).
- ✗A cache shared across customers: it leaks data from one to another and violates the LGPD (Brazil’s data protection law).
- ✗Agents that execute actions: repeating the answer doesn’t repeat the right action.
Why learn
The two caches reduce cost in different ways: prompt caching lowers the cost of the long context that repeats in every call; semantic caching eliminates entire calls. Knowing which one to use—and how to order the prompt so prompt caching works—often saves money without changing models.
Key concepts
🌎 Multi-region and resilience
Model providers go down, slow down, and enforce rate limits during peak hours—that’s part of operating the system, not an exception. When AI is on the critical path (customer support, checkout, triage), the architecture needs a plan for that. The components are familiar from systems engineering: health check (a periodic test that a destination responds), circuit breaker (after consecutive failures, the system stops retrying a destination for a while and uses the alternative) and graceful degradation (offer a reduced version of the feature instead of an error).
AI adds a complication: where data may be processed. Sending the prompt to a region in another country during failover may count as an international transfer of personal data, which the LGPD regulates. That’s why the alternative route needs prior approval from legal and security teams—not a rushed decision at three in the morning. Two numbers guide the design: RTO, how long the service can be down, and RPO, how much data (conversations, memory, indexes) you can afford to lose.
What it is
Multi-region resilience means keeping the AI service running when a provider, model, or region fails: approved alternative destinations, health checks, a circuit breaker, replicated context data, and a planned degraded mode.
Level 1 · Retry with increasing delays. Handles transient errors and brief rate limits. Always set a maximum number of attempts.
Level 2 · Model fallback. Another model from the same provider or a local model for simple tasks.
Level 3 · Provider or region fallback. Requires a contract, a quality assessment of the alternative model, and data residency approval.
Level 4 · Degraded mode. Prewritten responses, a queue for later processing, or routing to human support—with an honest notice to the user.
Why learn
The more AI becomes part of critical processes, the more a provider outage can become a business outage. A resilience plan written before an incident—with approved routes, defined RTO and RPO, and a tested degraded mode—is what separates an hour of slow service from a day of halted operations.
Key concepts
💰 Cost limits at scale
AI costs vary by call, and users partly control the size of each call: a huge pasted document, a conversation that never ends, or an agent caught in a loop calling tools. Without limits, a single customer or bug can use up the month’s budget over a weekend. AI FinOps is the practice of measuring, attributing, and controlling this spending with the same discipline applied to the cloud.
Limits work in layers, all at the gateway: rate limit (calls or tokens per minute, per key), per-call cap (maximum input and output tokens), per-tenant budget (monthly amount, with alerts before it runs out), and step limit for agents. Tenant means each customer, department, or product that uses the platform and needs its spending tracked separately. When it reaches the limit, the best response is rarely a blunt error: switch to a cheaper model and notify the user.
What it is
Cost limits are rules applied before each call—rate, size, per-tenant budget, and agent steps—with the actual cost recorded afterward, so spending is predictable, attributable, and automatically cut off when it exceeds the agreed limit.
Goal: a per-tenant budget guard, with a per-minute limit and fallback to the cheaper model.
"""guarda_orcamento.py — per-tenant limits before each call. Run: python3 guarda_orcamento.py"""
import time
from collections import defaultdict
# R$ per 1 million tokens. EXAMPLE VALUES: replace them with the ones in your contract.
PRECOS = {"rapido": {"entrada": 0.0, "saida": 0.0}, # local: the cost is the machine, not the token
"forte": {"entrada": 15.0, "saida": 60.0}}
ORCAMENTO_MES = {"cliente-a": 50.0, "cliente-b": 0.12} # R$ per month
LIMITE_MINUTO = {"cliente-a": 60, "cliente-b": 3} # calls per minute
gasto = defaultdict(float)
janela = defaultdict(list)
class Bloqueado(Exception):
pass
def custo(modelo, tok_in, tok_out):
p = PRECOS[modelo]
return (tok_in * p["entrada"] + tok_out * p["saida"]) / 1_000_000
def autorizar(tenant, modelo, tok_in, tok_out_max):
agora = time.time()
janela[tenant] = [t for t in janela[tenant] if agora - t < 60]
if len(janela[tenant]) >= LIMITE_MINUTO[tenant]:
raise Bloqueado(f"{tenant}: per-minute limit (return HTTP 429)")
escolhido = modelo
if gasto[tenant] + custo(modelo, tok_in, tok_out_max) > ORCAMENTO_MES[tenant]:
if modelo == "rapido":
raise Bloqueado(f"{tenant}: monthly budget exhausted")
escolhido = "rapido" # downgrade instead of denying the request
janela[tenant].append(agora)
return escolhido
def registrar(tenant, modelo, tok_in, tok_out):
gasto[tenant] += custo(modelo, tok_in, tok_out) # use the ACTUAL usage returned by the API
if __name__ == "__main__":
for i in range(1, 6):
for tenant in ("cliente-a", "cliente-b"):
try:
m = autorizar(tenant, "forte", tok_in=2000, tok_out_max=800)
registrar(tenant, m, 2000, 500)
print(f"{tenant} call {i}: via {m:6} | spend R$ {gasto[tenant]:.4f}")
except Bloqueado as e:
print(f"{tenant} call {i}: BLOCKED — {e}")
How to check: client-a should make all 5 calls via "forte". client-b should make the 1st call via "forte", the 2nd and 3rd via "rapido" (budget nearly exhausted), and be BLOCKED on the 4th and 5th (3-per-minute limit). If the output looks like this, all three layers — budget, downgrade, and rate limiting — are working. In production, store spend e window in Redis or the database, not in process memory.
✓ Limits that work
- ✓Applied at the gateway, consistently across all applications.
- ✓Tiered alerts (for example, at half, three-quarters, and the full budget).
- ✓Step and token caps for each agent run.
- ✓Cost per product feature, not just per provider bill.
✗ Limits that fail
- ✗Only the provider's billing alert, which arrives after the spending.
- ✗A single API key shared by all teams.
- ✗A hard error when the limit is exceeded, with no downgrade or warning.
- ✗Cost estimated from the prompt, without checking the actual usage returned.
Why learn
Managers approve AI at scale when costs are predictable. With a budget per tenant, automatic downgrading, and costs attributed to each product feature, the conversation shifts from "the bill was high" to "this feature costs this much per user, and it's worth it" — the foundation for any investment decision.
Key concepts
🧭 Architecture review in practice
Everything you've seen comes together in an architecture review: before an AI system goes into production, or when it starts to grow, someone works through the layers with specific questions. The order matters — measure before optimizing, and set cost limits before opening access to all customers.
An AI assistant can help make the review more thorough, as long as you provide the real context and prohibit invented numbers. It doesn't replace measurement; it helps surface questions the team hasn't asked, organize risks, and propose a work order for you to validate.
What it is
A seven-step review checklist, from metrics to cost limits, plus an analysis prompt that turns a description of your system into a prioritized list of decisions, each with a way to measure it.
1 · Metrics. Is there a dashboard with p95, TTFT, error rate, tokens, and cost per tenant and per feature?
2 · Gateway. Does any application call a model directly using its own key? If so, that should be the first task.
3 · Routing. What portion of the traffic is simple? Do you have an evaluation set to prove the smaller model can handle it?
4 · Caching. Does the fixed prefix come before the variable part? Are there repeated questions that justify semantic caching separated by tenant?
5 · Inference. Is the volume stable enough to compare API costs with a self-hosted server on a cost-per-million-tokens basis?
6 · Resilience. Are RTO and RPO defined? Is there an approved fallback route for the data being transmitted? Has degraded mode been tested?
7 · Cost. Is there a budget per tenant, a cap per call, a limit on agent steps, and an alert before the end of the month?
Goal: review your AI system's architecture with an assistant (Claude, ChatGPT, Gemini).
You are a senior AI systems architect reviewing a design before it scales. Rule: do not invent prices, latencies, or percentages. When you need a number, write the formula with variables and say how I can measure the value. CONTEXT - What the system does: <3-line description> - Volume: <calls per day, peak per minute, average prompt and response size> - Acceptable latency: <desired p95, whether the response is streamed> - Models and providers in use today: <list> - Data being processed: <types; any personal data? where can it be processed (LGPD)?> - Customers/tenants: <how many, whether spending needs to be separated> - Monthly budget: <amount or "not defined"> - What already exists: <gateway? cache? metrics? fallback?> TASK 1. Before analyzing, ask up to 5 questions about what is missing. 2. Evaluate each layer: metrics, gateway, routing, cache, inference, resilience, cost. For each: current state, main risk, recommendation. 3. List the 3 biggest risks (technical, financial, legal), from most to least serious. 4. Provide a table with 5 prioritized decisions: Decision | Layer | Effort (low/medium/high) | Impact | How to measure before and after 5. Say what you CANNOT evaluate with this information alone.
How to check: The response should start with questions, not recommendations; each decision in the table needs a concrete metric (p95, cost per tenant, cache hit rate). Look for numbers without formulas—if you find any, ask for their source or suggest replacing them with variables. Take the table to the team and validate each row against real data before acting on it.
Why learn
Technical leaders rarely design systems alone; they lead reviews. A fixed guide ensures no layer is overlooked, and the analysis prompt speeds up the first draft without replacing real measurement with the model’s opinion.
Key concepts
✅ Module summary
Next module:
3.2 — Custom and Proprietary Models 🧬