The cheatsheet

Every concept as the one sentence you'd say in an interview, plus the numbers worth memorizing. Filter, skim, print.

LLM Fundamentals

Models read, limit and bill text in tokens: subword chunks from a fixed vocabulary, ~4 characters or ~0.75 words of English each. Spanish, code and non-Latin scripts need more tokens per idea.

  • English: ~4 characters or ~0.75 words per token; 100 tokens ≈ 75 words.
  • Vocabulary sizes: GPT-2 50,257; cl100k_base ~100k; o200k_base ~200k; Llama 3 128,256.
  • Spanish typically needs ~20–50% more tokens than English for the same text, depending on the tokenizer.

An embedding model turns text into a fixed-length vector so that similar meanings land close together; compare vectors with cosine similarity to search, cluster, classify or deduplicate by meaning instead of keywords.

  • Common dims: 384 (all-MiniLM-L6-v2), 768 (BERT-base class), 1,024, 1,536 and 3,072 (OpenAI text-embedding-3-small / -large).
  • Storage: dims × 4 bytes per float32 vector; 1M × 1,536 ≈ 6.1 GB. int8 is 4× smaller, binary 32×.
  • Unit vectors: cosine = dot product, and L2² = 2 − 2·cosine, so all three rank identically.

A decoder-only transformer embeds tokens, runs them through N identical blocks of attention plus MLP joined by residuals, and outputs next-token logits. It trains on all positions in parallel, which is why it beat RNNs.

  • Params ≈ 12 × layers × d_model² for a classic block; GPT-3: 12 × 96 × 12,288² ≈ 174B.
  • Llama 3 8B: 32 layers, d_model 4,096, 32 query / 8 KV heads, MLP width 14,336, vocab 128,256.
  • MLPs hold ~2/3 of each block classically; ~81% in Llama 3 8B (SwiGLU + GQA), ~70% of all params.

Each token builds a query, key and value; it scores its query against every earlier token's key, softmaxes the scores and takes a weighted sum of values. Cost grows O(n²) with context length.

  • Score matrix per head per layer: n² entries; 32k tokens ≈ 1.07B entries.
  • Doubling context ≈ 4× attention FLOPs but only 2× KV cache.
  • KV cache per token = 2 × layers × KV heads × head_dim × bytes; Llama 3 8B in bf16 ≈ 128 KiB.

The maximum tokens a model handles in one call, input and output combined: 128k to 1M+ today. Usable quality degrades well before the advertised limit, and every token costs money and latency.

  • 128k tokens ≈ ~96k English words ≈ ~300 pages.
  • Common windows (2025–26): 128k (GPT-4o, Llama 3.1), 200k (Claude ≤4.5), ~1M (Gemini 2.5 Pro, GPT-4.1, Claude 4.6+).
  • Output caps are separate and smaller: 16,384 tokens for GPT-4o, 65,536 for Gemini 2.5 Pro.

The model scores every token; decoding picks one. Use low temperature for facts, code and tool calls, higher temperature with top-p or min-p for variety. Even temperature 0 isn't bit-for-bit reproducible.

  • OpenAI API temperature 0–2 (default 1). Anthropic: 0–1 on older Claude models; Opus 4.7/4.8, Sonnet 5 and Haiku 5.5 reject non-default temperature, top_p and top_k with a 400 (release notes, May–Oct 2026).
  • Common truncation settings: top_p 0.9–0.95; min_p 0.05–0.1.
  • Thinking Machines: 1,000 runs of one prompt at T=0 on Qwen3-235B gave 80 distinct completions; batch-invariant kernels made them identical.

During generation, store every token's attention keys and values so each new token reuses them instead of recomputing the prefix; the price is GPU memory that grows with context length × concurrent requests.

  • Per token: 2 × layers × kv_heads × head_dim × bytes per value.
  • Llama-3.1-8B fp16: 128 KiB/token → ~16 GiB at 128k tokens, about the size of its weights.
  • Llama-3.1-70B fp16: 320 KiB/token → ~40 GiB per 128k-token sequence.

Pretraining on trillions of tokens builds knowledge into a base model; SFT teaches it to follow instructions; preference tuning (RLHF/DPO) shapes style and safety; RL with verifiable rewards teaches it to reason on checkable problems.

  • Pretraining data: Llama 3 ~15T tokens; DeepSeek-V3 14.8T.
  • Llama 3.1 405B: ~3.8×10^25 FLOPs on up to 16k H100 GPUs.
  • DeepSeek-V3: ~2.79M H800 GPU-hours in total, only ~5K of them post-training.

Loss falls predictably as a power law in parameters, data and compute. Chinchilla's compute-optimal mix is ~20 tokens per parameter, but labs overtrain small models because inference, not training, dominates lifetime cost.

  • Training ≈ 6·N·D FLOPs; inference ≈ 2·N FLOPs per token.
  • Chinchilla-optimal: ~20 tokens per parameter (70B on 1.4T tokens).
  • GPT-3: ~1.7 tokens/param; Llama 3 8B: ~1,875 tokens/param (15T tokens).

Replace the dense feed-forward block with many expert FFNs and a router that sends each token to only the top-k, so total parameters (capacity) grow while compute per token stays at the active subset.

  • Mixtral 8x7B: ~47B total, ~13B active (top-2 of 8 experts).
  • DeepSeek-V3: 671B total, 37B active (8 of 256 routed experts + 1 shared).
  • Qwen3-235B-A22B: 235B total, 22B active.

LLMs trained with RL to think at length before answering. You buy accuracy on hard problems by spending more thinking tokens, billed as output and paid for in seconds of latency.

  • o1 on AIME 2024: 74% pass@1 vs 12% for GPT-4o; 83% with 64-sample consensus.
  • DeepSeek-R1-Zero, pure RL: AIME 2024 pass@1 from 15.6% to 71.0%; R1 reached 79.8%.
  • Anthropic manual extended thinking: minimum budget_tokens is 1,024 (Claude 4.7+ uses adaptive thinking + effort instead).

LLMs predict plausible text, not true text, and training and benchmarks reward guessing over "I don't know". You can't remove hallucinations; you ground, verify, allow abstention and measure the residual rate.

  • SimpleQA (OpenAI): gpt-5-thinking-mini abstains 52%, errs 26%; o4-mini abstains 1%, errs 75%, at similar accuracy (22% vs 24%).
  • Kalai et al.: if ~20% of facts like birthdays appear once in training, expect ≥~20% hallucination on them.
  • Mata v. Avianca (2023): 6 invented case citations, $5,000 sanction.

Images and audio are encoded into token-like vectors the LLM reads alongside text. They cost tokens (~85 to a few thousand per image) and fail on tiny text, counting and precise spatial reasoning.

  • LLaVA-1.5: one 336×336 image → 576 visual tokens (24×24 patches of 14 px).
  • Claude (2026 docs): 1 token per 28×28 px patch; max 1,568 per image, 4,784 on Claude 4.7+.
  • GPT-4o: 85 tokens at low detail; a 1024×1024 image at high detail ≈ 765 tokens.

Encoders (BERT) read text in both directions and output vectors for classification, embeddings and rerankers. Decoders (GPT) predict the next token and generate. Decoder-only won the frontier; small encoders still win cheap, high-volume understanding.

  • BERT-base 110M / BERT-large 340M params; pretraining masks 15% of tokens.
  • DistilBERT: 40% smaller, 60% faster, keeps ~97% of BERT's language understanding.
  • ModernBERT (Dec 2024): 8,192-token context, 149M (base) / 395M (large) params.

Pick the cheapest model that clears your quality bar on your own evals, within latency, cost and compliance limits. Prove value with the best model, then route or distill down behind a swappable abstraction.

  • FrugalGPT: LLM cascades matched GPT-4 quality with up to 98% lower cost on its benchmarks.
  • List-price spread within one family: GPT-4.1 $2 vs GPT-4.1-nano $0.10 per M input tokens (20×, as of 2025).
  • 200 eval cases at ~90% accuracy → ±~4 points 95% confidence interval: smaller gaps are noise.

Prompting & Context Engineering

A prompt is a list of role-tagged messages: system for stable rules, user for data and the question, assistant for prior turns. Put long documents first, the question last, and stable parts before variable ones.

  • Anthropic: long docs (~20K+ tokens) on top and the query at the end gave up to ~30% better responses on complex multi-document inputs.
  • OpenAI GPT-4.1 guide: instructions both above and below long context beat either alone; if only once, put them above.
  • Anthropic cache reads bill at 10% of the base input price (5% on Opus/Sonnet 5.5, late 2026), for an identical prefix only.

Zero-shot gives only instructions; few-shot adds a handful of input→output examples, which teach format and edge cases better than prose. The model also copies their quirks, so choose them deliberately.

  • Start with 3–5 diverse examples (Anthropic's guidance); add more only if your eval improves.
  • Zhao et al. 2021: prompt format, example choice and order alone swung GPT-3 from near chance to near state-of-the-art.
  • Min et al. 2022: random labels in the demos barely hurt classification accuracy; format and label space carry much of the effect.

Have the model write intermediate steps before the answer: it buys accuracy on multi-step problems at the cost of tokens and latency. Reasoning models do it natively, so set their effort knob instead.

  • Zero-shot CoT (Kojima 2022): InstructGPT went 17.7% → 78.7% on MultiArith and 10.4% → 40.7% on GSM8K.
  • Few-shot CoT (Wei 2022): PaLM 540B on GSM8K 17.9% → 56.9%; gains appeared only at ~100B+ parameters.
  • Sprague et al. 2024 meta-analysis: CoT's benefit concentrates on math and symbolic reasoning, with much smaller gains elsewhere.

Don't ask for JSON, enforce it: strict schema mode masks every token that would break your schema, so output always parses. It guarantees shape, not truth, so still validate values and retry.

  • OpenAI eval: gpt-4o-2024-08-06 with Structured Outputs scored 100% on complex schema following; gpt-4-0613 scored under 40%.
  • Tam et al. 2024: stricter format constraints generally meant larger drops on reasoning tasks.
  • Rule of thumb: allow 1–2 retries with the validation error; if more than ~1% of calls need one, fix the schema or the prompt.

Treat the model like a brilliant new hire with zero context: say exactly what you want and why, separate data from instructions, show an example, and specify the output format.

  • Anthropic reports that putting the question after long documents improves response quality by up to ~30% on complex multi-document inputs.
  • Anthropic recommends 3–5 diverse, relevant examples for few-shot prompting.
  • OpenAI's GPT-4.1 guide: in long contexts, repeat key instructions at both the start and the end; XML delimited documents well, JSON poorly.

Deciding, at every step of an agent or pipeline, exactly which tokens enter the window (instructions, tools, documents, tool results, memory, history), aiming for the smallest set of high-signal tokens.

  • Anthropic: a sub-agent may explore with tens of thousands of tokens but returns a condensed summary of ~1,000–2,000 tokens.
  • Anthropic's multi-agent researcher: ~15× chat tokens; token usage alone explained ~80% of performance variance on BrowseComp.
  • Anthropic reported that clearing stale tool results cut token use by 84% in a 100-turn web-search eval.

The provider keeps the computed KV state of a recently seen prompt prefix, so repeat calls skip that prefill: put static content first, variable content last, and cut repeated input cost by up to ~90–95%.

  • Anthropic (late 2026): cache write 1.25× base input (5-minute TTL) or 2× (1-hour TTL); cache read 0.1×, or 0.05× on Opus and Sonnet 5.5.
  • Break-even with a 1.25× write and 0.1× read is the first reuse: two calls cost ~1.35× instead of 2×.
  • OpenAI (late 2026): on by default from 1,024 tokens; older models discount cached input 50–90% with no write fee; GPT-5.6+ charge 1.25× to write and 0.1× to read.

Stuff the whole corpus in the window when it's small, static and shared; use RAG when it's large, changing, permissioned or high-volume. Often you do both: retrieve whole documents, then reason in long context.

  • Anthropic's rule of thumb (2024): under ~200k tokens (~500 pages), consider skipping RAG and putting the whole knowledge base in the prompt, with caching.
  • Lost in the Middle (2023): GPT-3.5-Turbo's multi-document QA accuracy fell ~20 points when the answer moved from the start to the middle of 20 documents.
  • RULER (2024): only about half of models claiming 32k+ windows held satisfactory performance at 32k.

Models don't use long context evenly: facts in the middle get used worst, and quality decays as input grows even on easy tasks. Send less, better context, with key parts at the edges.

  • Liu et al.: ~20-point accuracy drop when the answer moves from the first to the middle position (GPT-3.5-Turbo, 20 documents).
  • RULER: of models claiming 32K+ context, only about half held up at 32K.
  • NoLiMa (2025): at 32K tokens, 11 of 13 models fell below 50% of their short-context score; GPT-4o went from 99.3% to 69.7%.

Treat every prompt as a deployable artifact: templated, versioned with its model and parameters, reviewed, eval-gated in CI, rolled out gradually and logged with every trace so you can roll back in seconds.

  • Rollout ladder: ~1–5% → 25–50% → 100%, holding at each step long enough to read online metrics.
  • Start the CI golden set at ~50–200 cases per prompt; it must finish in minutes or people skip it.
  • Registry fetches: client-side cache (TTL ~60 s, Langfuse's default) plus a bundled fallback, so an outage never blocks requests.

Sample several reasoning paths at temperature > 0 and keep the answer most of them agree on, or let a verifier pick the best. Buys accuracy and a confidence signal for N× the tokens.

  • Wang et al.: +17.9 points on GSM8K for PaLM 540B (40 sampled CoT paths vs greedy CoT).
  • OpenAI o1 on AIME 2024: 74% with one sample, 83% with consensus over 64, 93% reranking 1,000 samples with a learned scorer.
  • Cobbe et al.: a trained verifier on GSM8K gave roughly the boost of a 30× larger model.

Stop hand-tuning prompts: define the task, an eval set and a metric, and let an optimizer search instructions and few-shot examples that maximize the metric. Prompts become learned parameters you recompile per model.

  • OPRO: optimized prompts beat human-written ones by up to 8% on GSM8K and up to 50% on Big-Bench Hard tasks.
  • OPRO's top GSM8K instruction for PaLM 2-L, "Take a deep breath and work on this problem step-by-step": 80.2% vs 71.8% for "Let's think step by step".
  • MIPRO: beat baseline optimizers on 5 of 7 multi-stage programs with Llama-3-8B, by up to 13% accuracy.

RAG & Retrieval

Before the model answers, search your own data for the most relevant passages and put them in the prompt, so the answer is grounded in fresh, private, citable sources instead of memory.

  • Typical online shape: retrieve ~50 → rerank → 3–8 chunks of ~300–800 tokens in the prompt.
  • Indexing is cheap: 75M tokens with text-embedding-3-small ($0.02 per 1M, list price as of 2026) ≈ $1.50.
  • Retrieval + reranking usually add ~100–400 ms before the first token; generation dominates total latency.

Turn messy PDFs, slides, scans and web pages into clean, structured text with metadata before chunking; most RAG quality problems start here, not in the model.

  • Managed OCR lists at ~$1.50 per 1,000 pages; layout or table extraction ~$10–15 per 1,000 (Azure, AWS list prices, 2026).
  • Under ~100–200 extracted characters per page usually means a scan that needs OCR.
  • Read 20–50 parsed documents by eye before tuning anything downstream.

Split documents into retrievable pieces that are each about one thing yet carry enough context to answer; chunk size is a precision-vs-context trade-off you settle with evals, not defaults.

  • Common starting point: 300–800 tokens per chunk with 10–20% overlap.
  • Parent-child: children ~100–400 tokens, parents ~1,000–2,000 tokens or a whole section.
  • Many open embedding models cap input at 512 tokens (some at 256); longer text is silently truncated.

Pick the embedding model by measuring retrieval on your own queries, then weigh dimensions, max input, languages, latency and price; leaderboards only shortlist, and switching later means re-embedding everything.

  • OpenAI text-embedding-3-small: 1,536 dims, $0.02 per 1M tokens; -large: 3,072 dims, $0.13 per 1M (list prices as of 2026); max input 8,191 tokens.
  • float32 storage = dims × 4 bytes: 1,024 dims ≈ 4 KB per vector, ~4 GB per 1M chunks.
  • OpenAI reports text-embedding-3-large cut to 256 dims still beats ada-002 at 1,536 dims on MTEB.

A database that stores embeddings with metadata and answers "the k nearest vectors to this one, where tenant = X" in milliseconds. Choose on scale, filtering, hybrid support and ops burden; often pgvector is enough.

  • 1M × 1536 dims × 4 B ≈ 6 GB of raw float32; int8 ≈ 1.5 GB; binary ≈ 0.2 GB.
  • pgvector indexes up to 2,000 dims for vector and 4,000 for halfvec.
  • pgvector HNSW defaults: m = 16, ef_construction = 64, hnsw.ef_search = 40.

Exact nearest-neighbor search scans every vector; ANN indexes visit a tiny fraction and accept missing a few true neighbors. HNSW is the default, IVF and PQ trade recall for memory, efSearch/nprobe are the dials.

  • Exact kNN over 10M × 768 float32 reads ~31 GB per query.
  • Common HNSW starting points: M = 16, efConstruction = 64–200, efSearch = 40–100 (and always ≥ k).
  • PQ at 1 byte per 16 dims: a 1536-dim float32 vector goes from 6 KB to 96 bytes (64×).

BM25 ranks documents by how often they contain your query's words, rewarding rare words and discounting long documents. Decades old, no model, and still better than embeddings at exact terms: IDs, error codes, product names.

  • Lucene, Elasticsearch and OpenSearch defaults: k1 = 1.2, b = 0.75.
  • BM25 has been Lucene's default similarity since Lucene 6.0 (2016).
  • IDF ≈ ln(1 + (N − n + 0.5)/(n + 0.5)): a term in 37 of 200k docs ≈ 8.6; in half the docs ≈ 0.7.

Run keyword (BM25) and vector search in parallel and merge the two rankings, usually with Reciprocal Rank Fusion. Each covers the other's blind spots, so recall rises for little extra cost.

  • RRF: score = Σ 1/(k + rank), with k = 60 from Cormack et al. (2009).
  • With k = 60: #1 in both lists ≈ 0.033; #1 in only one list ≈ 0.016; rank 10 is worth ~13% less than rank 1.
  • Typical shape: top ~50 per retriever → fuse → rerank → keep 3–8.

Retrieve many candidates cheaply, then let a slower, smarter model reorder them and keep only the best few for the prompt.

  • Typical shape: retrieve 50–100 → rerank → keep 3–8.
  • Anthropic measured contextual retrieval + reranking cutting top-20 retrieval failures by 67%.

Before retrieving, use a small LLM to turn the user's raw message into better search queries (standalone, expanded, decomposed or a hypothetical answer), paying one extra model call for recall.

  • Latency: +1 small-model call, ~0.2–1 s; produce rewrite, variants and HyDE passage in a single call.
  • Multi-query: 3–5 variants → retrieval fan-out ×3–5 → fuse with RRF, score = Σ 1/(60 + rank).
  • HyDE (Gao et al., 2022) is zero-shot: it beat the unsupervised Contriever retriever without any relevance labels.

At indexing time, an LLM writes 50–100 tokens situating each chunk in its document; you prepend them before embedding and BM25. Anthropic cut top-20 retrieval failures 49% (67% with reranking), at no query-time cost.

  • Top-20 retrieval failure rate in Anthropic's tests: 5.7% baseline → 3.7% with contextual embeddings (−35%).
  • Adding contextual BM25: 2.9% (−49%); adding reranking on top: 1.9% (−67%).
  • Generated context: ~50–100 tokens per chunk.

Attach metadata (tenant, ACL groups, date, type) to every chunk and enforce it as a hard filter inside the search, built in code, so the LLM never sees a document the user couldn't open.

  • Post-filter math: a user who can read a fraction p of the corpus keeps ~p·k of k hits; 1% of 100 ≈ 1.
  • Revocation delay = your ACL sync interval: a nightly batch can keep serving revoked access for up to ~24 h.
  • pgvector 0.8+ adds iterative index scans so filtered HNSW queries keep returning enough rows.

Answer only from retrieved chunks, tag every claim with the ids of the chunks that support it, verify those citations in code, and abstain when the context doesn't contain the answer.

  • Liu et al. (2023), auditing 4 generative search engines: only ~51.5% of generated sentences were fully supported by their citations.
  • Same study: only ~74.5% of citations actually supported the sentence they were attached to.
  • Citation precision = citations that support their claim ÷ all citations; citation recall = fully supported claims ÷ all claims.

An LLM turns the corpus into an entity–relation graph, clusters it into communities and pre-writes a summary of each, so you can answer corpus-wide questions that top-k chunk retrieval can't.

  • Indexing cost ≈ one extraction call per chunk (plus optional "gleaning" retries) + one report per community.
  • The GraphRAG paper evaluated on ~1–2M-token corpora (podcast transcripts, news articles).
  • In the paper, 600-token chunks extracted ~2× the entity references of 2,400-token chunks.
Agentic RAGAdvanced

Put retrieval inside an agent loop: the model decides whether, what and where to search, judges the evidence, and searches again until it can answer — accuracy on hard questions for latency, tokens and predictability.

  • N agent steps cost more than N× the input tokens of one-shot RAG: each call re-sends the growing transcript.
  • Self-RAG uses 4 reflection-token types: Retrieve, IsRel, IsSup, IsUse.
  • CRAG's retrieval evaluator is a fine-tuned T5-large (~0.77B params), not the generator LLM: grading can be cheap.

Store one vector per token instead of one per passage, and score with MaxSim at query time: precision close to a cross-encoder, with documents still pre-computed offline, paid for in storage.

  • ColBERT: 128-dim vector per token; queries padded or truncated to 32 tokens.
  • Uncompressed: 300 tokens × 128 dims × 2 bytes (fp16) ≈ 77 KB per chunk vs ~4 KB for one 1,024-dim fp32 vector.
  • ColBERTv2 residual compression (1–2 bits per dimension): 6–10× smaller index.

A RAG index is a replica of your sources: stream changes in, propagate every deletion, version each chunk, and migrate embedding models through a blue/green index and an alias swap, never in place.

  • GDPR: answer an erasure request without undue delay, normally within one month (Art. 12(3)).
  • Re-embedding 1B tokens with text-embedding-3-small ≈ $20 ($0.02 per 1M, list price as of 2026); throughput and rebuild time are the real bottleneck.
  • Embedding inversion (vec2text) recovered 92% of 32-token inputs exactly from their embeddings.

Score retrieval and generation separately: recall@k and MRR tell you whether the evidence was found, faithfulness and correctness tell you whether the model used it. One blended score hides which stage to fix.

  • MRR per question: first relevant doc at rank 1 → 1.0, rank 2 → 0.5, rank 5 → 0.2, not found → 0.
  • Hit rate@50 of 0.80 means ~20% of questions never see a relevant doc: no generator can fix those.
  • RAGAS core metrics: faithfulness, answer relevancy, context precision, context recall.

Agents & Tool Use

Workflow: your code fixes the path and the LLM fills in steps. Agent: the LLM picks each next step and tool in a loop. Go single call → workflow → agent, climbing only when needed.

  • Anthropic (2025): agents use ~4× the tokens of a chat interaction; multi-agent systems ~15×.
  • Compounding: at 95% per-step reliability a 10-step run succeeds ~60% of the time (0.95¹⁰ ≈ 0.60); at 99%, ~90%.
  • Anthropic's 49% on SWE-bench Verified (Claude 3.5 Sonnet, Oct 2024) used a minimal agent: one prompt, a bash tool, an edit tool, a loop.

The model never runs anything: it emits a tool name plus JSON arguments, your code validates and executes it, and the result goes back as a message so the model can continue.

  • τ-bench (2024): gpt-4o function-calling agents solved <50% of tasks, and pass^8 (all 8 retries succeed) was <25% in retail.
  • Anthropic adds a hidden tool-use system prompt whenever tools are passed: ~290–680 tokens depending on the model (e.g. 497 on Sonnet 4.6, 286 on Opus 5.5; docs, Nov 2026).
  • Rule of thumb: a tool definition costs ~50–300 tokens, so 30 tools add several thousand tokens to every call.

The canonical agent loop: the model thinks, picks an action, your harness runs it and feeds back the real observation, and it repeats until done or until a cap you set stops it.

  • ReAct paper: +34 and +10 points absolute success over imitation and RL baselines on ALFWorld and WebShop, prompted with only 1–2 examples.
  • On HotpotQA, ReAct alone slightly trailed chain-of-thought; combining it with self-consistent CoT scored best. On FEVER, ReAct beat CoT.
  • Cost math: step k re-sends k prior steps, so n steps send ~n²/2 step-sized chunks of input; Prompt caching makes the repeated prefix cheap.

Tool names, descriptions, parameters, outputs and errors are prompts the agent reads every call. Expose a few task-shaped tools, return concise results and actionable errors, and tune them on real-task evals.

  • Claude Code caps tool responses at 25,000 tokens by default (Anthropic, 2025).
  • OpenAI guidance: aim for fewer than ~20 functions available at once, a soft limit for accuracy.
  • SWE-agent (2024): with a purpose-built ACI, GPT-4 Turbo reached 12.5% pass@1 on SWE-bench; ablations showed interface details alone (edit linting, a windowed file viewer) changed the solve rate.

Split a task into a fixed sequence of LLM calls, each consuming the previous output, with code checks between steps: you trade extra latency for accuracy and per-step debuggability.

  • Reliability multiplies: five steps at 95% each ≈ 77% end-to-end (0.95⁵). Gates exist to break this math.
  • Latency is additive: end-to-end ≈ sum of step latencies, plus any retries the gates trigger.
  • A code gate costs microseconds and $0; an LLM-judge gate adds a full call (~0.5–3 s). Prefer code gates where possible.

Classify each input first, then send it to the prompt, model or pipeline built for that class: each path stays simple, and easy queries stop paying for the expensive model.

  • The smallest and largest tiers of one vendor often differ 5–20× per token: GPT-4.1 nano launched at $0.10 vs GPT-4.1 at $2.00 per 1M input tokens (Apr 2025 list prices).
  • RouteLLM (2024): learned routers cut cost by over 2× on some benchmarks without losing response quality.
  • FrugalGPT (2023): an LLM cascade matched GPT-4's performance with up to 98% lower cost on its benchmarks.

Run several LLM calls at once and merge them in code: sectioning splits a task into independent parts, voting runs the same task N times. You trade extra tokens for lower latency or higher confidence.

  • Rule of thumb: wall-clock ≈ max(branch latencies); cost ≈ sum of all branches.
  • Self-consistency (Wang et al., 2022): majority vote over ~40 sampled reasoning paths added +17.9 points on GSM8K over single-path chain-of-thought.
  • Independence math: 3 voters each catching 70% of bugs → any-of ~97%, majority ~78%. Only if their errors were independent, which they rarely are.

A central LLM reads the task, decides at runtime which subtasks it needs, delegates each to a worker LLM and synthesizes the results: parallelization where the model, not your code, writes the task list.

  • Anthropic (2025): an Opus 4 lead with Sonnet 4 subagents beat single-agent Opus 4 by 90.2% on its internal research eval.
  • Same post: agents use ~4× the tokens of chat; multi-agent systems ~15×.
  • In Anthropic's BrowseComp analysis, token usage alone explained ~80% of the performance variance.

One LLM generates, a second evaluates the output against explicit criteria and returns specific feedback, and the generator revises, looping until the output passes or a round limit is hit.

  • Self-Refine (2023): iterative self-feedback improved task performance by ~20% absolute on average across 7 tasks.
  • Reflexion (2023): feedback from test runs lifted HumanEval pass@1 to 91%, versus 80% for GPT-4 alone.
  • Huang et al. (2023): without external feedback, self-correction did not improve reasoning benchmarks and sometimes lowered accuracy.

A strong model writes an explicit step-by-step plan first; the steps are executed (often by a cheaper model with tools), and the agent replans only when a step fails or new facts appear.

  • ReWOO (Xu et al., 2023): ~5× token efficiency and +4% accuracy on HotpotQA versus interleaved reasoning.
  • LLMCompiler (Kim et al., 2023): up to 3.7× lower latency and 6.7× lower cost than ReAct by running the plan's DAG in parallel.
  • Rule of thumb: 3–10 steps per plan, each with a "done when" check; cap replans at 2–3, then escalate.
Agent memoryAdvanced

The context window is short-term memory; long-term memory lives outside the model (facts, past runs, rules) and is written, retrieved, updated and deleted by explicit policies, often exposed to the agent as tools.

  • Generative Agents (Park et al., 2023): retrieval score = recency + importance + relevance; recency decays by 0.995 per game hour, importance is rated 1–10 by the LLM.
  • Rule of thumb: inject ~5–10 memories (a few hundred to ~2k tokens) per turn, never the full transcript.
  • GDPR Art. 17 (right to erasure): deletion must reach memory rows, embeddings and derived summaries, not just the chat log.

An open standard (Anthropic, Nov 2024) for plugging AI apps into tools and data: servers expose tools, resources and prompts over JSON-RPC, so N apps and M integrations need N+M adapters, not N×M.

  • Launched Nov 2024; OpenAI, Google and Microsoft announced support between Mar and May 2025.
  • Two standard transports, stdio and Streamable HTTP (since spec 2025-03-26, replacing the original HTTP+SSE), and still the two in the 2026-07-28 revision. Current spec revision: 2026-07-28, the stateless one with no initialize handshake.
  • Integration math: 5 apps × 20 systems = 100 bespoke connectors; with MCP, 5 + 20 = 25 implementations.

An open protocol (Google, Apr 2025; v1.0 Mar 2026; now in the Linux Foundation's Agentic AI Foundation) for agents from different vendors to discover each other through an Agent Card and delegate long-running tasks over HTTP. It complements MCP (agent-to-tool).

  • Launched Apr 2025 by Google with 50+ partners; to the Linux Foundation in Jun 2025 (founding members include AWS, Cisco, Microsoft, Salesforce, SAP, ServiceNow); under its Agentic AI Foundation since Aug 2026.
  • Bindings: JSON-RPC 2.0, gRPC and HTTP+JSON over HTTPS, SSE streaming, webhook push; v0.3 (Jul 2025) added signed Agent Cards and the agent-card.json path.
  • v1.0 (12 Mar 2026): PascalCase operations (SendMessage, GetTask, new ListTasks), TASK_STATE_* enums, Parts without kind, supportedInterfaces replacing the card's url, mandatory A2A-Version header.

Split work across several LLM agents, each with its own context and role, to gain parallelism and context isolation — paying ~15× chat tokens and coordination failures. Worth it for broad, parallel, read-heavy tasks.

  • Anthropic research system: a single agent uses ~4× the tokens of a chat; multi-agent ~15×.
  • Anthropic: an Opus 4 lead with Sonnet 4 subagents beat single-agent Opus 4 by 90.2% on its internal research eval.
  • Anthropic: token usage alone explained ~80% of the performance variance on BrowseComp.

Agents that operate a GUI like a person: read a screenshot, then click, type and scroll. They reach apps without APIs, but are slow, brittle, costly and open to prompt injection from any page.

  • OSWorld: humans ~72%; Claude 3.5 Sonnet ~15% (Oct 2024); OpenAI CUA 38.1% (Jan 2025); Claude Sonnet 4.5 61.4% (Sep 2025, OSWorld-Verified); Claude Opus 4.6 72.7% (Feb 2026, reported).
  • OpenAI CUA (Jan 2025): 58.1% on WebArena and 87% on WebVoyager — curated web tasks are easier than full desktops.
  • Claude image cost = ⌈width/28⌉ × ⌈height/28⌉ visual tokens (28-px patches, ≈ width × height / 750): a 1280×800 screenshot ≈ 1,334 tokens, every step; Claude 4.7+ models take up to 2,576 px and 4,784 tokens per image (docs, Nov 2026).

Persist the agent's state after every step so it survives crashes, deploys and multi-day human waits: resume from the last checkpoint, retry steps with idempotency keys, never re-run what already succeeded.

  • AWS Step Functions: Standard workflows run up to 1 year; Express workflows up to 5 minutes.
  • Step Functions caps each state's input/output at 256 KB: keep transcripts in S3 and pass pointers.
  • Temporal: event history caps at 51,200 events or 50 MB per execution; use Continue-As-New for long agents.

Put a human approval gate in front of consequential or irreversible agent actions, tiered by risk, and escalate low-confidence cases — while keeping prompts rare enough that reviewers still read them.

  • Rule of thumb: tier by blast radius — read-only auto, writes approve, money/deletes/permissions explicit confirm.
  • Alert-fatigue precedent: clinicians override 49–96% of drug-safety alerts (van der Sijs et al., 2006).
  • Anthropic: sandboxing cut Claude Code permission prompts by 84% internally — fewer prompts, more attention per prompt.

Agents fail by compounding small errors and by looping. Bound every run with step, token, time and dollar budgets, detect repeated calls, feed errors back structurally, checkpoint, and give tools least privilege.

  • Compounding: 0.95^20 ≈ 36%, 0.99^20 ≈ 82%, 0.90^10 ≈ 35%.
  • τ-bench (2024): GPT-4o solved <50% of tasks, and pass^8 in retail fell below 25%.
  • Rule of thumb: cap steps at ~2–3× the median successful run; stop on the 3rd identical tool call.

Evaluation

Write the evals before or with the feature, like TDD: the eval suite is the spec, and every prompt, model or retrieval change ships only if the suite's numbers say it's better.

  • Rule of thumb: start with ~20–50 cases drawn from real failures; hundreds come later, from production traces.
  • Noise floor: at n=100 and an 80% pass rate, the 95% CI is ~±8 points; at n=1,000, ~±2.5.
  • Hamel Husain's three levels: assertions on every commit → human + model eval on a cadence → A/B tests for big changes.

Read ~100 real traces, write a free-form note on each failure, group the notes into failure modes, count them, and fix the biggest bucket first. Automate evals only for modes you actually found.

  • Rule of thumb: review ~100 traces per round, and keep going until new traces stop revealing new failure modes.
  • Typical shape (rule of thumb): a handful of modes, often 3–6, covers most failures: Pareto, not uniform.
  • Effort (rule of thumb): with a good trace viewer, 100 traces is a few hours of reading, not days.

A curated, versioned set of inputs with expected outputs or grading criteria, covering the slices that matter. It's the fixed ruler every change is measured against; without it, scores aren't comparable.

  • Rule of thumb: start with ~50–200 cases; grow toward several hundred to ~1,000 as slices multiply.
  • At an 80% pass rate the 95% CI is ~±8 points with 100 cases and ~±4 with 400.
  • A 25-case slice at 80% carries a ~±16-point 95% CI: per-slice reads need more cases or bigger effects.

Grade LLM outputs with plain code wherever the answer is checkable: exact match, regex, schema validity, right tool and arguments, SQL results, unit tests. Cheap, instant and reproducible, so try them before any LLM judge.

  • HumanEval: 164 hand-written Python problems, graded by unit tests and reported as pass@k (Chen et al., 2021).
  • Unbiased pass@k from n samples with c correct: 1 − C(n−c, k) / C(n, k), averaged over problems.
  • SWE-bench: 2,294 real GitHub issues from 12 Python repos, graded by running each repo's own tests.

Use a strong LLM with a narrow rubric to grade outputs at scale, but treat it as a classifier: calibrate it against human labels, report agreement, and counter position, verbosity and self-preference bias.

  • Zheng et al. (2023): on MT-Bench, GPT-4 as judge agreed with human experts on >80% of non-tie votes, about the level humans reach with each other.
  • Same paper: with the answer order swapped, even GPT-4 kept its verdict only ~65% of the time.
  • Rule of thumb: calibrate on ~100–200 human-labeled examples; aim for judge TPR and TNR of ~0.9 or better.

Domain experts are your source of truth: they label a few hundred examples under written guidelines, you verify they agree (Cohen's kappa), and those labels validate your automated judges instead of grading everything.

  • Landis & Koch (1977) kappa bands: 0.41–0.60 moderate, 0.61–0.80 substantial, 0.81–1.00 almost perfect.
  • Why kappa: if both raters mark ~90% PASS, chance agreement is 82%, so 90% raw agreement is only κ ≈ 0.44.
  • Rule of thumb: ~50 double-labeled items to estimate agreement; ~100–200 labels to calibrate a judge.

Every guardrail, router or judge is a classifier: read its confusion matrix, set the threshold by what each error costs, and prefer precision, recall and PR-AUC over accuracy when positives are rare.

  • F1 = 2PR / (P + R): precision 0.9 with recall 0.5 gives F1 ≈ 0.64, not the 0.7 average.
  • Base rate: at 1% prevalence, 99% recall with a 1% false-positive rate still gives only ~50% precision.
  • Random baselines: ROC-AUC = 0.5 at any class balance; PR-AUC = the positive rate (e.g. 0.01).

Split the answer into atomic claims, check each against the provided context with an NLI model or LLM judge, and report the unsupported share per slice. Faithful-to-context is not the same as factually true.

  • RAGAS faithfulness = claims supported by the retrieved context ÷ total claims in the answer (0–1).
  • FActScore (Min et al., 2023): only ~58% of the atomic facts in ChatGPT-generated biographies were supported.
  • Vectara HHEM scores each (source, claim) pair from 0 (hallucinated) to 1 (consistent); 0.5 is a common cut-off; tune it on labeled data.

Run each task several times in a sandbox; grade the outcome (the end state) and the trajectory (required and forbidden tool calls, steps, cost), and report pass^k: users need reliability, not one lucky run.

  • τ-bench (Yao et al., 2024): gpt-4o function-calling agents solved <50% of tasks, and pass^8 was <25% in the retail domain.
  • Independent trials at 90% per-trial success: pass^8 = 0.9^8 ≈ 43%, while pass@8 ≈ 100%.
  • SWE-bench: 2,294 real GitHub issues from 12 Python repos, graded by the repo's tests; SWE-bench Verified is a 500-task human-validated subset.

Same input, different outputs: one eval run is a sample, not a measurement. Run several trials, report mean ± confidence interval, and choose pass@k (any success) or pass^k (every success) to match real use.

  • 95% CI half-width ≈ 1.96·√(p(1−p)/n): at 50%, n=100 → ±~10 pts; n=400 → ±~5; n=1,000 → ±~3.
  • pass^k ≈ p^k for independent trials: 90% per run → ~73% for 3 in a row, ~59% for 5.
  • Codex (2021): 28.8% of HumanEval with 1 sample, 70.2% with 100 samples per problem.

Offline evals score a version on fixed datasets before deploy; online evals measure live traffic through user behavior, feedback and sampled judging. You need both, and if they disagree, trust neither until you know why.

  • Rule of thumb: canary at ~1–5% of users, then staged ramps (e.g., 25% → 50% → 100%) gated on guardrails.
  • Judge precision depends on volume, not percentage: ~400 judged traces give ±~5 pts at 95%, ~100 give ±~10.
  • GitHub Copilot study (Ziegler et al., 2022): the acceptance rate of shown suggestions predicted perceived productivity better than other usage metrics.

Randomly split users between old and new model or prompt, compare one pre-chosen primary metric, and let guardrails (latency, cost, safety) veto. Size it with a power analysis; never stop at the first significant peek.

  • Lehr's rule: n per arm ≈ 16·p(1−p)/δ² (80% power, α=0.05). Baseline 50%: +2 pts → ~10,000 per arm; +1 pt → ~40,000.
  • Peeking: 10 interim looks at p < 0.05 push the real false-positive rate to ~19% (Armitage et al.).
  • 20 metrics at α=0.05 → ~64% chance at least one shows a false "win" (1 − 0.95²⁰).

Public benchmarks measure generic capability on fixed test sets, and many are saturated or contaminated by training data. Use them to shortlist two to four models, then decide on your own eval set.

  • Sizes: HumanEval 164 problems; GPQA Diamond 198; SWE-bench Verified 500; MMLU ~16k questions in 57 subjects.
  • SWE-bench (2023): the best model solved 1.96% of issues; by late 2025, top models reported ~80% on SWE-bench Verified (each vendor's own harness).
  • GPQA: experts with or pursuing PhDs score ~65% (~74% excluding clear mistakes); skilled non-experts with web access ~34%.

Run the eval suite automatically on every prompt, model, retrieval or tool change, and block the merge or release when scores fall below floors or regress versus the baseline beyond noise.

  • Rule of thumb: PR subset of ~50–200 cases in under ~10 minutes; full suite nightly and before each release.
  • Noise floor: at n=200 and an 85% pass rate, one run's 95% CI is ±~5 pts. Set regression thresholds above it or add trials.
  • Dated snapshots (e.g., gpt-4o-2024-08-06) stay fixed; aliases like gpt-4o get repointed to newer snapshots over time.

Fine-tuning & Adaptation

Climb only as high as you must: prompt, few-shot, RAG for missing knowledge, fine-tuning for behavior, format or cost. RAG adds facts; fine-tuning changes form. Pretraining is almost never the answer.

  • LIMA: ~1,000 curated examples taught LLaMA-65B the assistant format (Zhou et al., 2023).
  • InstructGPT: labelers preferred a 1.3B tuned model over 175B GPT-3. Adaptation can beat size.
  • Price gap between a frontier model and its small sibling: often ~10–20× per token (GPT-4o vs GPT-4o mini was ~16× at late-2024 list prices).

Keep training a pretrained model on (prompt, ideal response) pairs so it imitates them. It teaches format, style and task behavior; a few thousand curated examples usually beat a million noisy ones.

  • LIMA: ~1,000 curated examples aligned LLaMA-65B competitively (Zhou et al., 2023).
  • InstructGPT's SFT set was only ~13k prompts with labeler-written answers.
  • OpenAI's SFT guide: minimum 10 examples; gains typically from 50–100 (platform closed to new users, 2026).

Freeze the model and train a low-rank update per weight matrix: usually under 1% of parameters, saved as a megabyte-sized adapter. QLoRA stores the frozen base in 4-bit, so big models fine-tune on one GPU.

  • LoRA on GPT-3 175B: ~10,000× fewer trainable parameters, ~3× less GPU memory, checkpoint 350 GB → ~35 MB.
  • QLoRA: 65B model fine-tuned on one 48 GB GPU, matching 16-bit fine-tuning (Dettmers et al., 2023).
  • 8B model, r=16 on all linear layers: ~42M trainable parameters, about 0.5%.

Humans pick the better of two answers, a reward model learns those preferences, and PPO pushes the model toward high reward while a KL penalty keeps it near the original. It turned GPT-3 into InstructGPT.

  • InstructGPT: labelers preferred the 1.3B RLHF model over 175B GPT-3, with 100× fewer parameters.
  • InstructGPT data: ~13k SFT prompts, ~33k reward-model prompts, ~31k PPO prompts, ~40 contract labelers.
  • InstructGPT ranked 4–9 responses per prompt, giving up to 36 pairs per ranking.

Tune a model directly on (prompt, chosen, rejected) pairs with a simple classification-style loss: the RLHF objective without a reward model or an RL loop, so it is cheaper and far more stable than PPO.

  • β ≈ 0.1 is the usual default (TRL's); sweeps commonly span ~0.01–0.5.
  • Memory: PPO-based RLHF holds 4 models (policy, reference, reward, value); DPO holds 2; ORPO and SimPO hold 1.
  • Zephyr-7B: SFT + DPO on ~60k GPT-4-scored UltraFeedback pairs beat Llama-2-70B-chat on MT-Bench.

Reinforcement learning where a program, not a person, scores each answer (tests pass, result matches). GRPO makes it cheap: sample a group of answers per prompt and reinforce those that beat the group average.

  • DeepSeek-R1-Zero: AIME 2024 pass@1 rose from 15.6% to 71.0% with pure RL (86.7% with majority voting).
  • GRPO group size: commonly 8–64 samples per prompt; TRL's default is 8.
  • Rule of thumb: keep prompts the model solves ~10–90% of the time; all-pass or all-fail groups give zero advantage.

Train a small student to imitate a large teacher, via its probabilities or its generated text, keeping most of the quality on your task at a fraction of the cost and latency.

  • DistilBERT: ~40% smaller (66M vs 110M parameters), ~60% faster, keeps ~97% of BERT's GLUE performance.
  • DeepSeek-R1-Distill-Qwen-32B: 72.6% AIME 2024 pass@1 vs o1-mini's 63.6%, from SFT alone on ~800k R1-curated samples.
  • Same paper: distilling R1 into Qwen-32B beat running large-scale RL on it directly (72.6% vs ~47% on AIME).

Use LLMs to generate training or eval data, then filter, dedup and verify it. It's cheap coverage for rare cases, but it inherits the generator's blind spots, so humans still check eval labels.

  • Self-Instruct: 175 human seed tasks grew into ~52k instructions; Stanford's Alpaca reproduced it for under $500 of API calls.
  • Nemotron-4 340B: over 98% of the data used in its alignment process was synthetic.
  • phi-1 (1.3B): 50.6% HumanEval pass@1, trained on ~6B filtered web tokens plus ~1B tokens of GPT-3.5-written textbooks and exercises.

Quality beats quantity: remove exact and near duplicates, filter junk with heuristics and classifiers, decontaminate against evals, scrub PII and balance the mix. A smaller clean set routinely beats a bigger dirty one.

  • LIMA: 1,000 curated SFT examples; its answers were equal to or preferred over GPT-4's in 43% of comparisons.
  • Lee et al.: C4 held one 61-word sentence 60,000+ times; deduplication cut verbatim memorized output ~10×.
  • FineWeb-Edu: ~1.3T of FineWeb's ~15T tokens, kept by a classifier trained on ~450k Llama-3-70B ratings.

Fine-tuning on narrow data overwrites what the model already knew, degrading general skills, instruction following and even safety. Mitigate with LoRA, general-data replay, lower learning rates and fewer epochs, and gate on general evals.

  • Qi et al. 2023: 10 adversarial examples and under $0.20 of API fine-tuning jailbroke GPT-3.5 Turbo's safety guardrails.
  • Biderman et al. 2024: full fine-tuning learns weight changes of 10–100× higher rank than typical LoRA configs.
  • Rule of thumb: 1–3 epochs for SFT; more epochs, more forgetting.

Keep training a base model with the plain next-token objective on billions of unlabeled domain tokens so it absorbs a new domain or language; powerful but expensive, and for most enterprises RAG plus SFT wins.

  • Training compute ≈ 6 × params × tokens FLOPs: 8B params on 10B tokens ≈ 4.8e20, ~340 H100-hours at 40% MFU.
  • Code Llama: Llama 2 continued on 500B code tokens (+100B Python tokens for the Python variant).
  • Meditron: Llama 2 continued on ~48B tokens of medical text.

Train your retriever on domain (query, relevant passage) pairs with a contrastive loss, using LLM-generated queries and mined hard negatives. A tuned embedder means re-indexing everything; a tuned reranker doesn't.

  • MNRL: a batch of B pairs gives each query B−1 free in-batch negatives; default scale 20 (temperature 0.05).
  • Rule of thumb: ~1k–10k good pairs move a base-size (~110M) model; training takes minutes to an hour on one GPU.
  • Rule of thumb: sample hard negatives from ranks ~10–50, not the top few, where false negatives live.

Split training across GPUs by data (replicate model, split batch), by state (FSDP/ZeRO shard weights, gradients, optimizer), inside layers (tensor) or across layers (pipeline). Mixed-precision Adam needs ~16 bytes per parameter.

  • Mixed-precision Adam ≈ 16 bytes/param before activations: 7B ≈ 112 GB, 70B ≈ 1.1 TB.
  • ZeRO-3/FSDP: per-GPU state ≈ 16 × params / N, at ~1.5× DDP's communication volume.
  • Pipeline bubble ≈ (p−1)/(m+p−1) of step time: 4 stages, 16 micro-batches → ~16% idle.

Inference, Serving & Cost

Split LLM latency into TTFT (wait for the first token: queueing + prefill) and TPOT (gap between later tokens: decode), track p95/p99, and size capacity by goodput, the throughput that still meets both SLOs.

  • E2E ≈ TTFT + TPOT × (output tokens − 1); per-user speed = 1/TPOT (20 ms → 50 tokens/s).
  • People read ~200–300 words/min ≈ ~4–7 tokens/s; streaming at ~10+ tokens/s outpaces them.
  • MLPerf Inference Llama-2-70B server limits (p99): TTFT ≤ 2 s, TPOT ≤ 200 ms; the v5.0 interactive scenario tightens them to 450 ms and 40 ms.

Prefill reads the whole prompt in one parallel, compute-bound pass and sets TTFT; decode then emits one token per step, bound by memory bandwidth, and sets TPOT. Most serving optimizations target one phase.

  • Forward pass ≈ 2 FLOPs per parameter per token: an 8B model prefilling 2k tokens ≈ 32 TFLOPs.
  • Batch-1 decode ≈ 1 FLOP per byte of FP16 weights; an H100 needs ~300 (989 TFLOPS ÷ 3.35 TB/s) to be compute-bound.
  • Output lists at ~4–8× input (2025 list prices): GPT-4o $2.50 vs $10, Claude Sonnet $3 vs $15 per million tokens.

Weights take parameters × bytes (70B in FP16 ≈ 140 GB), the KV cache gets what's left and that leftover sets concurrency; batch-1 decode speed is capped at memory bandwidth ÷ weight bytes.

  • Weights: 70B ≈ 140 GB in FP16, ~70 GB in FP8, ~35 GB in INT4 (+ scales).
  • KV per token in FP16: Llama-3-8B 128 KiB, Llama-3-70B 320 KiB.
  • H100 SXM: 80 GB HBM3 at ~3.35 TB/s; H200: 141 GB at ~4.8 TB/s; A100 80 GB: ~2 TB/s.

Re-form the batch at every decode step: finished sequences leave and queued requests take their slots at once, instead of everyone waiting for the longest member. It's the main reason engines get several-fold more throughput.

  • Orca: 36.9× throughput over NVIDIA FasterTransformer at the same latency (GPT-3 175B).
  • Anyscale benchmark: up to ~23× throughput vs naive static batching (with vLLM), while also lowering p50 latency.
  • vLLM (PagedAttention + continuous batching): 2–4× throughput over FasterTransformer and Orca at the same latency.

Store the KV cache in small fixed-size blocks allocated on demand, like OS memory pages, so almost no GPU memory is wasted; the freed memory becomes bigger batches and 2–4× throughput.

  • Pre-vLLM servers used only 20–38% of KV memory for real tokens; vLLM wastes under 4%.
  • 2–4× throughput vs FasterTransformer/Orca at equal latency (paper); up to 24× vs plain HF Transformers (vLLM launch blog).
  • Sharing cuts the memory of parallel sampling and beam search by up to 55% (vLLM blog).

A GPU kernel that computes exact attention block by block in fast on-chip memory, never writing the n×n score matrix out, so memory grows linearly with length and attention runs ~2–4× faster.

  • A100: ~20 MB of on-chip SRAM at ~19 TB/s vs 40–80 GB of HBM at ~1.5–2 TB/s.
  • FA-1: 3× faster GPT-2 training at 1k tokens; 10–20× attention memory saving at 2k–4k.
  • FA-2: ~2× FA-1, reaching 50–73% of A100 peak FLOPs/s.

Store weights (and optionally activations and KV cache) in 8 or 4 bits instead of 16: 2–4× less memory and faster decode; nearly free at 8-bit, a quality cost to measure at 4-bit.

  • Bytes per parameter: BF16 2, FP8/INT8 1, INT4 0.5. A 70B model is ~140 / ~70 / ~35 GB, plus ~5–10% for scales.
  • Rule of thumb: batch-1 decode ceiling ≈ HBM bandwidth ÷ weight bytes. 8B on an H100 (3.35 TB/s): ~200 tok/s in BF16, roughly 3× that in INT4.
  • GPTQ quantized 175B-parameter models to 3–4 bits in ~4 GPU hours.

A cheap draft guesses the next few tokens and the big model verifies them all in one forward pass, keeping those it agrees with: ~2–3× lower latency with exactly the target's output distribution.

  • Leviathan et al.: 2–3× on T5-XXL with identical outputs; Chen et al.: 2–2.5× on Chinchilla 70B.
  • Expected tokens per target pass = (1 − α^(k+1)) / (1 − α); acceptance α = 0.8, k = 4 → ~3.4.
  • Medusa-2: 2.3–3.6×; EAGLE: 2.7–3.5× on LLaMA2-Chat 70B (papers).

An inference engine (vLLM, SGLang, TensorRT-LLM) does the batching and KV-cache work on the GPUs; a platform layer (Kubernetes, KServe, Ray Serve, Dynamo) routes, scales on queue depth and hides minutes-long cold starts.

  • Weights ≈ params × bytes: 70B in BF16 ≈ 140 GB → at least 2× 80 GB GPUs, usually 4 for KV-cache headroom.
  • vLLM pre-allocates 90% of GPU memory by default (--gpu-memory-utilization 0.9), mostly for KV cache.
  • SGLang paper (2023): up to 6.4× higher throughput than prior systems on structured, prefix-sharing workloads.

Start with a managed API for speed and frontier quality; self-host open weights only when data control, custom weights or steady high utilization justify owning GPUs and on-call.

  • A month is ~730 hours: a rented GPU bills all of them, busy or idle.
  • Self-host cost per token = GPU $/hour ÷ tokens per hour actually served: halve utilization, double the unit cost.
  • Batch APIs cut prices ~50% for results within 24 h (OpenAI, Anthropic, Gemini).

Cost = input tokens × input price + output tokens × output price, summed over every call. Estimate per request, multiply by volume, then pull the levers: caching, shorter prompts, smaller models, batch.

  • ~4 characters ≈ 1 token ≈ 0.75 English words (OpenAI rule of thumb).
  • Output ~4–8× input on 2025 list prices per 1M: GPT-4.1 $2/$8, Claude Sonnet 4 $3/$15, GPT-5 $1.25/$10.
  • Cached input reads: ~0.1× base on Anthropic; 50–90% off on OpenAI depending on the model.

Send each request to the cheapest model that can handle it, by rules, a learned classifier or a cascade that escalates on a failed check, and fall back to another provider on outages.

  • RouteLLM (LMSYS, 2024): over 2× cost reduction at similar quality; ~85% cheaper than GPT-4-only on MT Bench at 95% of its quality.
  • FrugalGPT (2023): cascades matched GPT-4 quality at up to 98% lower cost on its benchmarks.
  • Cascade cost = small + P(escalate) × large: a 20× cheaper model with 25% escalation costs ~30% of all-large.

Reuse a stored answer when a new query's embedding is close enough to an earlier one: it skips a full generation, but every false hit serves a confident wrong answer.

  • Typical cosine threshold ~0.90–0.95 on normalized embeddings; tune it on labeled query pairs (rule of thumb).
  • A hit = one embedding call + one vector lookup: tens of ms vs seconds for a generation.
  • text-embedding-3-small: $0.02 per 1M tokens (OpenAI list price, unchanged as of Nov 2026), so lookups are close to free.
LLM gatewayAdvanced

One proxy in front of every model provider: apps call a single API, and the gateway handles keys, per-team token quotas, retries and fallbacks, caching, redaction, logging and cost attribution in one place.

  • Provider limits are two-dimensional: requests/min and tokens/min (Anthropic splits input and output TPM). Your quotas must be too.
  • Retry 429, 500/502/503, 529 (Anthropic overloaded) and timeouts with backoff + jitter; never retry 400/401/403.
  • Rule of thumb: a gateway should add single-digit ms per call, negligible next to hundreds of ms of TTFT.

Send tokens to the user as they are generated, over Server-Sent Events, so they start reading at time-to-first-token instead of waiting for the whole answer; total time is unchanged.

  • Nielsen's response-time limits: ~0.1 s feels instant, ~1 s keeps the flow of thought, ~10 s loses attention. Aim for TTFT under ~1 s.
  • Rule of thumb: hosted models decode ~50–100 output tokens/s per stream, so a 500-token answer is 5–10 s unstreamed.
  • Browsers allow ~6 HTTP/1.1 connections per origin; open SSE streams count against it, so serve them over HTTP/2.

When nobody waits on a single answer, submit the whole job offline: provider batch APIs give ~50% off with results within 24 h, and self-hosted runs push GPUs to peak throughput.

  • OpenAI Batch and Anthropic Message Batches: ~50% off standard prices, results within 24 h, often much sooner.
  • Per batch: OpenAI up to 50,000 requests and 200 MB; Anthropic up to 100,000 requests or 256 MB.
  • Anthropic keeps batch results for 29 days, and its batch discount stacks with prompt caching.

Record every request as a trace with one span per step (retrieval, model call, tool call), carrying prompt version, tokens, latency, cost and feedback, so you can explain, price and replay any answer.

  • OTel GenAI core attributes: gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens. Capturing message content is opt-in.
  • Rule of thumb for sampling: metrics on 100% of requests; full payloads on all errors and negative feedback plus ~1–10% of the rest.
  • Rule of thumb: ~4 characters per English token, so payload storage is ~4 bytes × tokens per span.

Security, Safety & Governance

LLMs can't reliably tell instructions from data, so any text in context can hijack them. No complete fix exists: limit what a hijacked model can do. The model proposes; deterministic code authorizes.

  • Term coined Sept 2022 (Simon Willison); indirect injection formalized Feb 2023 (Greshake et al.).
  • #1 in the OWASP Top 10 for LLM apps in every edition so far: 2023, 2025 and 2026 (LLM01).
  • Rule of thumb: a 99%-accurate detector still lets 1 in 100 attempts through, and attackers retry. In security, 99% is a failing grade.

An agent with private data, exposure to untrusted content and a way to communicate externally can be tricked into leaking that data. Injection can't be prevented, so remove at least one leg.

  • 3 legs; removing any 1 closes this exfiltration path (not the others).
  • 0 clicks: a rendered markdown image fetches its URL automatically, a classic exfiltration channel.
  • Rule of Two (Meta, Oct 2025): at most 2 of the 3 properties per session; all 3 needs human supervision.

A jailbreak gets a model to violate its own safety policy; the attacker is usually the user. Unlike prompt injection, it attacks the model's training, not your app. Defend in layers: model, classifiers, monitoring.

  • Constitutional Classifiers (Anthropic, Feb 2025): automated jailbreak success 86% → 4.4%, with +0.38% refusals and 23.7% compute overhead.
  • Their 2024 bug bounty: 183 red-teamers, 3,000+ hours, no universal jailbreak; the Feb 2025 public demo (~3,700 hours) produced one.
  • Many-shot (Anthropic, 2024): success scales with shot count; one prompt-classification mitigation cut attack success from 61% to 2%.

OWASP's community list of the ten most critical risks in LLM applications (2026 edition, LLM01–LLM10). Use it as a design-review checklist: for each item, name the control in your architecture or the accepted risk.

  • 10 risks, LLM01–LLM10; current edition is 2026 (published Aug 2026); earlier editions 2025 (Nov 2024) and 2023.
  • Prompt Injection is #1 in all three editions; Sensitive Information Disclosure has been #2 since 2025.
  • 2026: 8 of 10 entries changed rank; Excessive Agency rose from #6 to #3, Improper Output Handling fell from #5 to #10.

Independent checks on what goes into the model, what comes out, and which actions it may take: useful layers that cut risk, while the real boundary is deterministic permissions on actions.

  • Llama Guard 3: 8B with 14 MLCommons hazard categories (S1–S14), 1B with 13 (no S14 code-interpreter abuse); Llama Guard 4 (2025): 12B, multimodal, 14 categories.
  • Meta's Prompt Guard 2 injection/jailbreak classifier ships at 86M and 22M parameters: cheap enough to run on every request.
  • Rule of thumb: regex <1 ms, small classifier ~10–50 ms, LLM-based guard ~0.2–1 s or more if run in series.

Detect and redact or pseudonymize personal data before it reaches the model, logs or indexes; pick providers with no training and short or zero retention; and make deletion reach every copy, vectors and caches included.

  • GDPR fines: up to €20M or 4% of global annual turnover, whichever is higher.
  • GDPR: answer an erasure or access request within 1 month; notify the authority of a breach within 72 h.
  • OpenAI API data isn't used for training by default (since March 2023); abuse-monitoring logs are kept up to 30 days unless you have ZDR.

Tenant A must never reach tenant B's data through any path (retrieval, cache, memory, fine-tuned weights, logs): derive the tenant from auth, enforce it server-side at every layer, and prove it with tests.

  • ChatGPT, March 2023: a redis-py bug exposed payment details of ~1.2% of Plus subscribers active in a 9-hour window.
  • OpenAI documents that prompt caches are not shared between organizations.
  • Carlini et al. (2021) extracted hundreds of verbatim training sequences from GPT-2, including names, phone numbers and emails.

Attack your own AI system, with expert humans and automated tools, before launch and on every change; rate findings by severity and turn each one into a regression eval.

  • Anthropic released ~39k human red-team attacks (Ganguli et al., 2022), a public seed set for your own suite.
  • PAIR, an attacker LLM refining prompts against a target model, often finds a jailbreak in under 20 queries.
  • Rule of thumb: report attack success rate (ASR) per category per release; any open critical finding blocks launch.

Every model file, dataset, package and MCP server you pull is code or influence you didn't write: load weights as safetensors, pin hashes, scan and sign artifacts, serve only from a vetted internal registry.

  • ~250 poisoned documents were enough to backdoor models from 600M to 13B parameters, regardless of size (Anthropic, UK AISI, Turing Institute, Oct 2025).
  • Poisoning 0.01% of LAION-400M via expired domains would have cost ~$60 (Carlini et al., 2023).
  • A 2024 study found ~20% of packages suggested in LLM-generated code did not exist: names an attacker can register.

Alignment is the post-training that makes a model helpful, honest and harmless; it's statistical, vendor-controlled and shifts between versions, so treat it as a soft layer and re-run your evals on every upgrade.

  • InstructGPT (2022): outputs of the 1.3B RLHF model were preferred over those of the 175B GPT-3.
  • Alignment faking (2024): Claude 3 Opus complied with harmful requests ~14% of the time when it believed the chat would be used for training, almost never otherwise.
  • OpenAI rolled back a sycophantic GPT-4o update in April 2025, days after release.

Measure quality per user group, not just on average; document what the system is for and where it fails; keep humans able to intervene; and keep monitoring after launch.

  • Four-fifths rule (US EEOC guidelines, 1978): a group's selection rate below 80% of the top group's signals adverse impact.
  • Gender Shades (2018): commercial gender classifiers erred up to 34.7% on darker-skinned women vs 0.8% on lighter-skinned men.
  • Model cards: Mitchell et al., 2019. Datasheets for datasets: Gebru et al., 2018.
EU AI ActAdvanced

The EU regulates AI by risk tier: some uses are banned, high-risk uses need risk management, logging, human oversight and conformity assessment, chatbots and deepfakes need disclosure, and fines reach €35M or 7% of turnover.

  • In force 1 Aug 2024; bans and AI literacy from 2 Feb 2025; GPAI model obligations from 2 Aug 2025; Art. 50 transparency from 2 Aug 2026.
  • Digital Omnibus (Reg. (EU) 2026/1744, in force 27 Jul 2026): Annex III high-risk from 2 Dec 2027, Annex I products from 2 Aug 2028; new NCII/CSAM bans from 2 Dec 2026.
  • Fines up to €35M or 7% of worldwide annual turnover for banned practices; up to €15M or 3% for most other breaches.

NIST AI RMF is a voluntary playbook (Govern, Map, Measure, Manage) for finding and treating AI risks; ISO/IEC 42001 is a certifiable management system proving you do it consistently. Run both off one risk register.

  • NIST AI RMF 1.0: released 26 Jan 2023; 4 functions, 7 trustworthiness characteristics.
  • NIST AI 600-1 Generative AI Profile (July 2024): 12 GenAI risk categories.
  • ISO/IEC 42001 (Dec 2023): Annex A lists 38 reference controls under 9 objectives (A.2–A.10).

AI Architecture

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.

  • 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.

Every AI design choice trades quality, latency and cost, plus risk. Set a bar for each, know which lever moves which corner, and pick from the measured Pareto frontier instead of arguing.

  • OpenAI latency guide: halving output tokens can cut latency ~50%; halving the prompt often only ~1–5%.
  • Price spread inside one family: GPT-4.1 $2 vs GPT-4.1-nano $0.10 per 1M input tokens (20×, 2025 list).
  • RouteLLM (2024): ~85% cheaper than GPT-4-only on MT Bench at 95% of its quality.

LLM providers fail loudly (outages, 429/529) and quietly (latency spikes, quality regressions). Time out fast, retry with backoff, trip circuit breakers, fail over to an evaluated backup, then degrade gracefully.

  • Serial availability: a 99.9% app on a 99.5% model API ≈ 99.4%. An independent fallback lifts the model tier to ~99.997% (independence is optimistic).
  • The Tail at Scale (Google): a hedged request after 10 ms cut p99.9 latency from 1,800 ms to 74 ms with only 2% more requests.
  • Google SRE: at most 3 attempts per request; keep retries under ~10% of a client's traffic.

An agent acts for a user: give it short-lived, narrowly scoped, delegated tokens capped by the user's rights; authorize every tool call in code, confirm risky ones, and audit each action to the human.

  • RFC 8693 (Jan 2020) defines OAuth token exchange; its act claim records who is acting for whom.
  • AWS STS role sessions last 15 min to 12 h, default 1 h; role chaining caps them at 1 h.
  • Microsoft Entra access tokens default to a random 60–90 minute lifetime (75 on average).

One AI request can pass eight caches, from the CDN down to the GPU's KV cache. Each saves different latency or dollars; key every one by tenant, permissions and model, prompt and index version.

  • Anthropic prompt caching: reads ~0.1× base input; 5-minute default TTL refreshed on each hit, 1-hour option at a 2× write.
  • OpenAI caches prompts automatically from 1,024 tokens; caches are not shared between organizations.
  • Anthropic (2024): caching a 100k-token prompt cut time to first token from 11.5 s to 2.4 s.

Hosted models retire on published schedules, so every model you ship is a future migration: pin versions, hide providers behind one interface, and move only through an eval-gated path of shadow, canary and rollback.

  • Anthropic: ≥60 days' notice before retiring a public model; Claude Sonnet 4.5 was deprecated Sep 30, 2026 and retires Nov 30, 2026.
  • OpenAI's stated minimums (2026): ≥6 months for GA models, ≥3 months for specialized variants, as little as ~2 weeks for previews.
  • Recent Claude snapshots were retired ~1–2 years after release (Sonnet 3.7: Feb 2025 → Feb 2026).

Turn usage into improvement: log traces and feedback, select and label the informative cases, use them for evals first and training second, ship, and let more usage feed the next turn.

  • Cursor Tab (Sep 2025): online RL on accept/reject signals from 400M+ daily requests → 21% fewer suggestions, 28% higher accept rate.
  • Tesla (Karpathy, CVPR 2021): 221 shadow-mode triggers and 7 data-engine loops built ~1M 10-second clips, ~6B labeled objects, 1.5 PB.
  • GitHub Copilot study (Ziegler et al., 2022): acceptance rate predicted perceived productivity better than how long the code persisted.

At a billion vectors, memory is the design constraint: compress the vectors, move the index to SSD or object storage, shard and replicate, and rescore a small candidate set at full precision.

  • 1B × 768 dims: float32 ≈ 3.07 TB, int8 ≈ 0.77 TB, binary or 96-byte PQ ≈ 96 GB.
  • DiskANN (NeurIPS 2019): 1B SIFT points on one machine with 64 GB RAM plus SSD, >5,000 QPS, <3 ms mean latency, ≥95% 1-recall@1.
  • Hugging Face (Mar 2024): binary quantization kept ~92.5% of retrieval quality, ~96% with rescoring; int8 kept ~97%.

Run the model on the device instead of the cloud: you win latency, privacy, offline use and near-zero cost per query, and pay with small models, tight memory and a fleet to update.

  • Apple (2024): ~3B on-device model, mixed 2/4-bit at ~3.7 bits/weight; ~0.6 ms per prompt token and ~30 tokens/s on iPhone 15 Pro.
  • Weights ≈ params × bits ÷ 8: 3B at 4-bit ≈ 1.5 GB; at 16-bit ≈ 6 GB, too much for most phones.
  • Rule of thumb: decode tokens/s ≲ memory bandwidth ÷ weight bytes; ~50 GB/s ÷ 1.5 GB ≈ ~30 tokens/s.

AI System Design Cases

Run the round as a chain of decisions: clarify the goal and costliest failure, size it, sketch offline and online paths, deep-dive with an eval per choice, then guardrails, failure modes and trade-offs.

  • 50-minute split: clarify 6 · estimate 4 · architecture 9 · deep dives 14 · eval 5 · safety 4 · serving 3 · failures 3 · close 2.
  • QPS = requests/day ÷ 86,400: 1M/day ≈ 12 QPS average; assume peak ≈ 2–3× average.
  • Tokens/day = requests × (input + output); output tokens cost ~4–8× input tokens on major APIs.

Connectors sync documents and ACLs into a hybrid index; at query time, filter by the user's permissions, retrieve and rerank, then answer only from cited chunks, or abstain.

  • Corpus: 10M docs × ~4 chunks (assumed) = 40M chunks; 1,024-dim float32 ≈ 164 GB of vectors, ~41 GB at int8.
  • Load: 50k employees × 40% daily active × 5 questions = 100k/day ≈ 3.5 QPS over 8 working hours, ~7 at a 2× peak.
  • LLM: 100k × (5k in + 400 out) = 0.5B in + 40M out tokens/day ≈ $2.1k/day at an assumed $3/$15 per M; ~$260 at $0.40/$1.60.

An agent answers from help-center RAG and proposes actions through narrow typed tools; a gateway and policy engine authorize every call, risky actions wait for a human, and hard cases hand off with context.

  • Volume: 1M users × 0.3 contacts/month (assumed) ≈ 300k conversations/month ≈ 10k/day.
  • LLM calls: 10k × ~6 = 60k/day; over 10 busy hours with a 2× peak, ~3–4 calls/s.
  • Tokens: ~6k in per call (system, tools, history) × 6 ≈ 36k in + ~2k out per conversation → ~360M in + 20M out/day.

Stateless chat servers build each turn's context under a token budget, route to a small or large model, stream tokens over SSE, and persist conversations in a sharded store behind per-user quotas.

  • Traffic: 10M DAU × 15 messages/day = 150M/day ≈ 1.7k msg/s; ×3 at peak ≈ 5k msg/s, or ~30k open SSE streams at ~6 s per answer.
  • Tokens: ~3k input (system + history + files) and ~400 output per message → 450B input + 60B output tokens/day.
  • Cost (assumed prices): 85% small at $0.15/$0.60 per 1M (~$88k) + 15% large at $2.50/$10 (~$259k) ≈ $350k/day ≈ $10M/month; large is 15% of traffic, ~75% of cost.

Three products on one context engine: a small fill-in-the-middle model for sub-300 ms inline completion, a large model for chat over a repo index, and an agent that edits and runs tests in a sandbox.

  • Completion budget ~300 ms: debounce ~75 + network ~40 + prefill ~40 + 15 tokens × ~8 ms ≈ 275 ms (~7B FIM model, nearby region).
  • Load: 100k seats × 40% typing at peak × 1 request per ~4 s after debounce ≈ 10k completion QPS.
  • Prefill-bound: 10k QPS × ~2.6k input tokens ≈ 26M prefill tok/s vs ~200k output tok/s (~20 each), so prefix caching dominates.

Hybrid retrieval (BM25 + embeddings) fetches ~1,000 candidates, a learning-to-rank model reorders them with business signals, and LLM query understanding is precomputed for head queries — all within 200 ms p99.

  • Traffic: 30M searches/day ÷ 86,400 ≈ 350 QPS average; ×10 on a holiday evening ≈ 3.5k QPS, and every query hits every shard.
  • Vectors: 50M × 768 dims × 4 B ≈ 154 GB in float32; int8 ≈ 38 GB + ~6 GB of HNSW links (M=16) per replica.
  • p99 budget 200 ms: parse 15 + embed 10 + retrieval 60 + features 15 + ranking 30 + facets 20 + network/headroom 50.

The PDF text layer or OCR feeds an LLM that fills a strict per-type schema; deterministic rules and calibrated per-field confidence decide what auto-posts and what a reviewer sees, and every correction feeds back.

  • Volume: 1M docs/month ≈ 33k/day ≈ 0.4/s; assume ~5× month-end peaks (~2/s) and 3 pages/doc → 3M pages/month.
  • Tokens: assume ~1k tokens/page + 1.5k cached prompt ≈ 4.5k in and ~0.4k out per doc → 4.5B input + 0.4B output tokens/month.
  • LLM: at an assumed $0.40/M input and $1.60/M output ≈ $1.8k + $0.6k = $2.4k/month list, ~$1.2k through a 50%-off batch API.

A tiered funnel: hash matching and cheap per-category classifiers settle ~97% of items in milliseconds, a policy-prompted LLM judges the borderline few percent, and humans handle the uncertain, the severe and appeals.

  • Load: 100k items/min ≈ 1.7k/s; plan for ~3× peaks ≈ 5k/s; ≈ 4.3B items/month. Assume 80% text, 20% images.
  • Funnel (assumed): hashes + classifiers settle ~97%; ~3% → LLM ≈ 50 req/s; ~0.05% → humans ≈ 72k items/day.
  • LLM via API: 130M calls/month × (3k cached policy + ~300 fresh + 100 output tokens) at an assumed $0.10/$0.40/$1.60 per M ≈ $39k + $16k + $21k ≈ $75k/month.

Retrieve relevant metrics, tables and verified queries; ask when ambiguous; generate a semantic-layer query or SQL; validate it deterministically; run it as the user; and show the result with its SQL and assumptions.

  • Load: assume 2,000 users × 10 questions per workday = 20k/day; over ~8 working hours ≈ 0.7/s, peaks ~2/s.
  • Tokens per question: ~3k schema + ~1.5k few-shot + ~1.5k instructions ≈ 6k in and ~0.4k out, × ~1.3 calls for clarifications and retries.
  • LLM: 440k questions/month (22 workdays) → ~3.4B input + ~0.23B output tokens; at an assumed $2/M in and $8/M out ≈ $6.9k + $1.8k ≈ $9k/month.

A fully streaming cascade (VAD and turn detection → streaming ASR → small, fast LLM with tools → streaming TTS) with barge-in and human transfer, targeting ~800 ms from end of speech to first audio.

  • Latency budget (p50): endpointing 200 + ASR final 75 + LLM TTFT 250 + first sentence 70 (~10 tokens at ~150 tok/s) + TTS first audio 100 + network 100 ≈ 800 ms.
  • Human turn gaps cluster around 0–200 ms across 10 languages (Stivers et al., 2009); past ~1.5 s, callers start repeating themselves or asking "hello?".
  • Audio: PSTN is G.711 at 8 kHz (64 kbit/s), WebRTC uses Opus at 48 kHz; pipelines move ~20 ms frames. Measure ASR accuracy on 8 kHz phone audio, not clean recordings.

A thin paved road: one mandatory LLM gateway (virtual keys, quotas, fallbacks, cost tags), opt-in shared services (prompt registry, evals, vector store, guardrails) and templates that make the right way the easy way.

  • Load: 100 teams, ~50M LLM calls/month ÷ 2.6M s ≈ 20 QPS average; at ~5× peak-to-average, plan for ~100 QPS plus long-lived streams.
  • Spend: 50M calls × (2k in + 300 out) = 100B input + 15B output tokens/month; at an assumed $1/M in and $5/M out ≈ $100k + $75k = $175k/month.
  • Logs: 50M calls × ~10 KB (prompt, response, metadata) ≈ 500 GB/month; keep full payloads ~30 days and metadata 13 months.

Pin dataset and agent versions, run each task k times in fresh seeded sandboxes, grade end state with code before judges or humans, store every trajectory, and gate releases on paired diffs with confidence intervals.

  • Full run: 500 tasks × 5 trials × ~30k tokens = 75M tokens ≈ $225 at an assumed $3/M blended; nightly ≈ $6.8k/month.
  • Wall clock: 2,500 episodes × ~3 min ÷ 200 parallel sandboxes ≈ 38 min; the CI time budget sets the parallelism.
  • Resolution: at an 80% pass rate the 95% CI half-width is ±~3.5 pts with 500 tasks and ±~10 with 60, so a PR smoke suite only catches large regressions.

Keep the classic funnel — two-tower ANN retrieval, a ranker, a diversity and rules re-rank — on the hot path; spend LLMs offline, once per item: enrichment, cold-start content embeddings, cached explanations.

  • Traffic: 10M DAU × 5 feed loads = 50M requests/day ≈ 580 QPS average, ~1,700 at a 3× peak; × 700 candidates ≈ 1.2M ranker scores/s at peak.
  • Enrichment: 50k new items/day × (1,500 input + 200 output tokens) = 75M in + 10M out; at $0.40/$1.60 per 1M (GPT-4.1-mini list price, Apr 2025) ≈ $46/day, ~$23 batched ≈ $700/month.
  • Counterfactual LLM re-ranker: 50M requests × ~5k tokens (profile + 50 candidates) = 250B tokens/day ≈ $100k/day of input at $0.40 per 1M, ~$3M/month, plus 1–3 s per request.

Scrub PII, then a small model in batch extracts schema-bound aspect opinions per review; code counts them; a writer model phrases pros/cons from the counts only; a verifier traces every claim before publishing.

  • Map: 500k new reviews/day × ~140 tokens (text + amortized prompt) = 70M in, ~30M out (2 rows × 30 tokens); at an assumed $0.40/$1.60 per 1M, −50% batch ≈ $38/day.
  • Reduce + verify on material change only: ~5% of 2M products = 100k/day × (~5k in + 0.6k out) at the same prices ≈ $150/day batched. Total ≈ $190/day ≈ $5.6k/month.
  • Naive daily re-summarization: 2M products × ~100 reviews × 100 tokens = 20B tokens/day ≈ $4k/day even batched (~20× more), and a 50k-review product (~5M tokens) fits no context window.

Gather ~1,000+ candidates, prune to ~500 with a light model, predict like, comment, share, hide and dwell with a multi-task model, combine them with tunable weights, then re-rank for diversity and integrity.

  • Traffic: 2B DAU × 10 feed loads/day (assumed) = 20B requests/day ≈ 230k QPS average, ~500k at a ~2× peak.
  • Main pass: 500k QPS × 500 candidates = 250M heavy scores/s at peak; the first pass scores ~3× more items at a fraction of the cost each.
  • One user-ID table: 3B rows × 128 dims × 2 bytes (fp16) ≈ 770 GB; add post, author and group tables and you are in TBs, sharded.

A sparse-embedding DNN, trained continuously on impression logs, predicts calibrated pCTR and pCVR; the auction ranks ads by bid × pCTR × pCVR (eCPM). Calibration is mandatory because predictions set prices, not just order.

  • Scoring: 1M ad requests/s at peak (assumed) × 150 heavy-ranked ads = 150M predictions/s, each with pCTR and pCVR heads.
  • Training rows: 10B impressions/day × 1% CTR = 100M positives, plus 2.5% of 9.9B negatives ≈ 250M → ~350M rows/day (assumed volumes).
  • Recalibration: true CTR 1%, w = 0.025 → the model sees 0.01 / (0.01 + 0.99 × 0.025) ≈ 29%; q = p / (p + (1 − p)/w) maps it back.

Score every payment in under ~100 ms: streaming velocity and graph features feed hard rules and a calibrated GBDT; an expected-cost policy picks approve, step-up, review or decline, and chargebacks weeks later retrain the model.

  • Load: 5k payments/s at peak (assumed) × ~6 entities (card, device, IP, email, account, merchant) = ~30k key-value multi-gets/s.
  • Latency p99 ~100 ms (assumed): network 10 + features 15 + graph 10 + rules 5 + GBDT ~2 + policy 3 ms; logging async; ~55 ms headroom.
  • Break-even (30% margin, $20 churn cost, $15 fee, assumed): $200 order p* = 80 / (80 + 215) ≈ 0.27; $20 order p* = 26 / (26 + 35) ≈ 0.43.

An async job clarifies and plans, fans out sub-agents with search and fetch in clean contexts, writes one cited report from their compressed findings, and verifies every citation, under token, time and dollar budgets.

  • Tokens per report (assumed): 5 sub-agents × ~12 turns × ~17k tokens of context re-read per turn ≈ 1M in; with lead, synthesis and checks ≈ 1.2M in, ~60k out.
  • Cost at an assumed $3/$15 per M (Nov 2026), plus ~60 searches at an assumed $5/1k: ~$4.80 uncached, ~$2.50 with ~70% of input as cache reads at ~10% price. At 100k reports/day: ~$250k/day.
  • Concurrency (Little's law): 100k reports/day ≈ 1.2 starts/s × ~600 s each ≈ 700 jobs in flight, ~1.4k at a 2× peak, each with up to ~5 live agent loops.

Rewrite the query, search, fetch and rerank passages from the top pages, then stream an answer citing a passage per claim; head queries hit a cache and the first token lands in ~1–2 s.

  • Load: 10M queries/day ≈ 115 QPS, ~300 at an assumed 2.5× peak; ~6.5k tokens in (5k passages + system and history) and ~300 out per query → ~65B in, ~3B out per day.
  • Per query at assumed Nov 2026 prices: small model at $0.40/$1.60 per M ≈ 0.3¢ + search at $5/1k = 0.5¢ → ~0.8¢; with a $3/$15 model ≈ 2.4¢ + 0.5¢.
  • First token: rewrite 120 ms + search 350 + fetch ≤ 800 + extract and rerank ~130 + prefill ~300 ≈ 1.7 s; source cards visible at ~0.5 s.

A gateway enforces per-tenant token quotas and tiers; a router sends each request to the replica holding its cached prefix and LoRA adapter; engine pools autoscale on queue depth and KV usage, from warm pools.

  • Assumed peak for the 70B flagship: 60k output + 600k input tokens/s (~3× average). Decode: 60k ÷ ~1,500 tokens/s per H100 (assumed goodput at p95 TPOT ≤ 50 ms, FP8) = 40 GPUs.
  • Prefill: 600k × 50% cache misses × 140 GFLOP/token (2 × 70B) ≈ 42 PFLOP/s ÷ ~800 TFLOPS effective per H100 (~40% of 1,979 FP8 dense) ≈ 53 GPUs.
  • Fleet: 93 GPUs + ~25% headroom for N+1 and bursts ≈ 120 H100s (30 TP=4 replicas, 15 nodes) ≈ $220k/month at an assumed $2.50 per GPU-hour (Nov 2026).

Cars run new models in shadow mode and upload clips when triggers fire; offline, big models auto-label the hard cases, training closes the loop, and scenario regressions plus simulation gate a staged OTA rollout.

  • Clip size: Tesla's CVPR 2021 dataset was 1.5 PB for one million 10-second clips ≈ 1.5 GB per clip at training quality.
  • Budget: 2M cars × ~1 h of driving/day (assumed) = 2M car-hours; a trigger firing once per car-hour yields 2M clips ≈ 3 PB/day, 20× a 100k-clip budget.
  • Ingest: 100k clips/day × 1.5 GB = 150 TB/day ≈ 14 Gbps sustained, ~55 PB/year before tiering and expiry.

ML Foundations

Supervised learning fits a function from labeled examples; what matters is error on unseen data, so you hold data out to measure it and balance underfitting (high bias) against overfitting (high variance).

  • Expected squared error = bias² + variance + irreducible noise σ².
  • Split rule of thumb: 80/10/10 or 70/15/15; with millions of examples, 98/1/1 still leaves 10k+ rows for val and for test.
  • k = 5 or 10 folds; Kohavi (1995) recommended stratified 10-fold CV for model selection.

Training means minimizing a loss: compute the gradient on a mini-batch and step weights the opposite way, scaled by the learning rate. Cross-entropy for classification, MSE for regression, AdamW with warmup for transformers.

  • Adam defaults: lr 1e-3, β1 0.9, β2 0.999, ε 1e-8 (Kingma & Ba); LLM pretraining often uses β2 0.95 (GPT-3, LLaMA).
  • LLaMA recipe: AdamW, weight decay 0.1, 2,000 warmup steps, cosine decay to 10% of peak LR, gradient clipping 1.0.
  • BERT fine-tuning grid: LR 5e-5, 3e-5 or 2e-5; batch 16 or 32; 2–4 epochs.

Regularization trades a little training fit for better generalization: penalize large weights (L2/L1), inject noise (dropout, augmentation, label smoothing) or stop before the model memorizes (early stopping).

  • Dropout paper: keep hidden units with p 0.5–0.8 (drop 20–50%), inputs ~0.8; original Transformer: dropout 0.1.
  • Label smoothing ε = 0.1 in Inception-v3 and the original Transformer.
  • Weight decay: 0.1 with AdamW in LLM pretraining (GPT-3, LLaMA); 1e-4 with SGD in the ResNet recipe.

A neural network stacks linear layers with nonlinear activations; backpropagation runs the chain rule backward from the loss to get every weight's gradient in one pass, which gradient descent then uses.

  • Sigmoid's derivative peaks at 0.25: across 10 sigmoid layers the activation factors alone can shrink gradients to 0.25¹⁰ ≈ 10⁻⁶.
  • Training ≈ 6·N FLOPs per token (2N forward, ~4N backward), i.e. ~3× inference (Kaplan et al., 2020).
  • He init for ReLU: weight variance 2/fan_in; Xavier/Glorot: 2/(fan_in + fan_out).

Build hundreds of small decision trees in sequence, each one fitting the errors the ensemble still makes; on tabular data XGBoost and LightGBM remain the default to beat.

  • XGBoost paper (2016): 17 of the 29 Kaggle challenge-winning solutions published in 2015 used XGBoost.
  • Grinsztajn et al. (NeurIPS 2022): on 45 datasets, trees still beat deep nets on medium-sized tabular data (~10K rows).
  • Defaults: XGBoost learning rate 0.3, max_depth 6; LightGBM learning rate 0.1, num_leaves 31. Rule of thumb: 0.01–0.1 plus early stopping.

Turn raw events into signals a model can use (scaled numbers, encoded categories, crosses, time-window aggregates) while making sure no feature peeks at the label or the future.

  • Kapoor & Narayanan: leakage affected ~300 published papers across 17 scientific fields (294 in the 2023 Patterns version).
  • Facebook ads (He et al., 2014): "the most important thing is to have the right features"; historical user and ad features dominated.
  • Rule of thumb: one-hot up to ~tens of categories; beyond that, target encoding, hashing or embeddings.

When positives are rare, fix the metric and the threshold before the data; when decisions use the probability itself (auctions, expected loss), calibrate it so a score of 0.02 really means 2%.

  • Cost threshold (Elkan, 2001): t = c_FP / (c_FP + c_FN); a $5 review vs a $100 missed fraud gives t ≈ 0.048.
  • Downsampling correction (He et al., Facebook, 2014): q = p / (p + (1 − p)/w), with w the negative sampling rate.
  • Focal loss (Lin et al., 2017): γ = 2, α = 0.25 worked best for RetinaNet; γ = 0 is plain cross-entropy.

Train a model to order candidates for a query or user so the best land on top: pointwise, pairwise or listwise losses, LambdaMART as the workhorse, NDCG@k to measure, debiased clicks as labels.

  • NDCG discount 1/log2(rank + 1): rank 1 = 1.0, rank 3 = 0.5, rank 10 ≈ 0.29.
  • An ensemble of LambdaMART rankers won Track 1 of the 2010 Yahoo! Learning to Rank Challenge (Burges, 2010).
  • MSLR-WEB30K benchmark: ~30K queries, 136 features per query–document pair, labels 0–4.

Choose among options one request at a time, shifting traffic toward the winners as evidence arrives, so you learn which is best while losing as little reward (regret) as possible.

  • UCB1 bonus √(2 ln t / nᵢ) gives regret O(log T) (Auer et al., 2002); a fixed-ε greedy policy has linear regret.
  • Lai & Robbins (1985): no policy beats ~log T regret growth; UCB and Thompson sampling match that order.
  • LinUCB on Yahoo!'s front page: 12.5% click lift over a context-free bandit (Li et al., 2010).

A backbone (a CNN sliding small filters, or a ViT attending over image patches) turns pixels into features; task heads turn them into labels, boxes or masks. Start from a pretrained backbone.

  • AlexNet (2012): 15.3% top-5 ImageNet error vs 26.2% for the runner-up, the start of deep learning in vision.
  • ResNet won ILSVRC 2015 at 3.57% top-5 error with up to 152 layers; ResNet-50: ~25.6M params, ~3.8 GFLOPs per image.
  • ViT-B/16 at 224×224: 196 patch tokens (+1 [CLS]), ~86M params.

Learn embeddings from pairs: pull matching items (image and caption, query and answer) together and push everything else in the batch apart. CLIP did this for images and text, enabling zero-shot classification and cross-modal search.

  • CLIP: ~400M image–text pairs, batch 32,768, learned temperature initialized at τ = 0.07 (logit scale capped at 100).
  • CLIP zero-shot ImageNet: 76.2% top-1, matching the original ResNet-50 without any of its 1.28M labeled training images.
  • SimCLR: a batch of 8,192 gives 16,382 negatives per positive pair (two augmented views per image).

Train a network to predict the noise added to real data; generate by starting from pure noise and removing predicted noise step by step. Quality, steps and latency trade off directly.

  • DDPM trains with T = 1,000 noise steps; DDIM samples in tens of steps, 10–50× faster wall-clock (Song et al., 2020).
  • Stable Diffusion v1: 512×512×3 → 64×64×4 latent (48× fewer values); ~860M-param U-Net plus a 123M CLIP text encoder.
  • CFG costs 2 denoiser passes per step; the diffusers Stable Diffusion pipeline defaults to guidance 7.5.

MLOps & ML Systems

ML is a loop, not a project: frame the problem, get labeled data, build features, train, evaluate, deploy, monitor and retrain. The model code is the small part; the pipeline around it is the system.

  • Google's maturity levels: 0 = manual, 1 = automated continuous training, 2 = CI/CD of the pipeline itself.
  • Google's level-0 description: a new model version is deployed only a couple of times per year.
  • Sculley et al. (NeurIPS 2015): ML code is only a small fraction of a real-world ML system.

LLMOps is MLOps where you mostly compose instead of train: the release unit is a pinned model plus prompts, retrieval index and tools, gated by eval suites, priced per token, and exposed to vendor deprecations.

  • Output tokens list at ~4–5× input (Nov 2026 list prices): $2 vs $10 per 1M on Claude Sonnet 5.5, $2.50 vs $10 on GPT-4o.
  • Batch APIs (OpenAI, Anthropic) cut price ~50% for jobs that can wait up to 24 h.
  • At n = 100 cases and a 50% pass rate, the 95% CI is about ±10 points: small eval sets can't see small regressions.

A feature store defines each feature once and serves it two ways: an offline store for point-in-time-correct training sets and an online store for millisecond lookups at inference, so training and serving agree.

  • Rule of thumb: online feature reads should be single-digit ms at p99, since a whole fraud or ranking call often gets ~50–100 ms.
  • Point-in-time rule: use the latest value with feature_ts ≤ label_ts, and only if it is within the feature's TTL.
  • Uber's Michelangelo (2017) popularized the offline/online feature store split.

The model sees different data or logic in production than it saw in training, so quality drops silently with no error. Fix it with one shared transformation path, logged serving features and automated skew checks.

  • Google's Rules of ML #29: log the features used at serving and train on them; #32: reuse code between training and serving.
  • Rule of thumb: in a parity check, more than ~1% of rows disagreeing on a feature means a code-path bug, not noise.
  • TFDV flags categorical skew by L-infinity distance between training and serving distributions (its guide uses a 0.01 threshold); Jensen-Shannon divergence also covers numeric features.

Data drift is when inputs change, P(X); concept drift is when the input-to-outcome relationship changes, P(Y|X). Detect the first with PSI or KS on features, the second mainly by tracking outcomes.

  • PSI rule of thumb: <0.1 stable, 0.1–0.25 moderate shift, >0.25 significant shift worth acting on.
  • PSI is usually computed on 10 reference bins (deciles); empty bins need a small floor to avoid log(0).
  • Two-sample KS at n = m = 100k: D above ~0.006 is already significant at p < 0.05.

A versioned catalog of deployable models with their lineage, metrics and approval state, so deploying and rolling back means moving a pointer, not retraining and hoping.

  • MLflow 2.9 (Dec 2023) deprecated the fixed Staging/Production stages in favor of free-form aliases (e.g. @champion, added in 2.8) plus tags.
  • Rule of thumb: keep the last 2–3 production versions loadable so rollback is instant.
  • Rule of thumb: an LLM release pins ~5 things together: model snapshot, prompt, retrieval index, tool schemas, guardrail config.

Log every run's code commit, data version, config, metrics and artifacts automatically, so any result can be compared, explained and rebuilt months later.

  • With 100 eval examples at ~80% accuracy, the 95% confidence interval is about ±8 points: a 2-point 'win' is noise.
  • Rule of thumb: compare model changes across 3–5 seeds and report mean ± std.
  • A reproducible run pins 4 things: code commit, data snapshot, environment digest, config with seeds.

Watch five layers (service health, input data quality, drift, model quality via proxies until labels arrive, business KPIs) and page only on the few that predict user harm.

  • PSI rule of thumb: < 0.1 stable, 0.1–0.25 moderate shift, > 0.25 significant shift.
  • Rule of thumb: run LLM-as-judge on ~1–5% of production traffic, more right after a release.
  • Google SRE: page when a 30-day SLO burns 2% of its error budget in 1 hour (14.4× burn rate).

Batch precomputes predictions on a schedule (cheap, stale); online computes them per request (fresh, latency-bound); streaming keeps features fresh from events. Choose by how fresh the decision must be, and usually mix them.

  • OpenAI Batch API and Anthropic Message Batches: 50% cheaper than synchronous calls, results within 24 h.
  • Rule of thumb: an interactive page has ~100–200 ms end to end; the model gets only a slice of it.
  • Kafka's default retention is 7 days (log.retention.hours=168): your window to replay events into a backfill.

A funnel: cheaply retrieve hundreds of candidates from millions (two-tower embeddings + ANN), rank them with a heavy model on rich features, then re-rank for diversity and business rules.

  • Covington et al. (YouTube, 2016): candidate generation narrows millions of videos to hundreds; ranking scores those to show dozens.
  • Netflix (Gomez-Uribe & Hunt, 2015): recommendations influence ~80% of hours streamed; the other ~20% comes from search.
  • Netflix Prize: $1M for a 10% RMSE gain (awarded 2009); the winning ensemble was never fully deployed, as the engineering cost outweighed the gain (Netflix Tech Blog, 2012).

Models are only as good as the data plumbing: a lakehouse with ACID tables, orchestrated pipelines, contracts, quality tests and lineage gives AI reproducible training data, fresh RAG sources and auditable evals.

  • Delta Lake defaults: VACUUM keeps 7 days of old files, the transaction log 30 days; older time travel needs an explicit snapshot.
  • Target file sizes: Iceberg defaults to 512 MB, open-source Delta OPTIMIZE to 1 GB (Databricks autotunes by table size); thousands of tiny files wreck scan speed.
  • Origins worth knowing: Delta Lake came from Databricks, Iceberg from Netflix, Hudi from Uber.

Distributed Systems

Order-of-magnitude arithmetic (latency, QPS, storage, tokens/s) done in two minutes to decide whether a design is feasible and which component dominates, before anyone builds anything.

  • L1 cache ~1 ns · main memory ~100 ns · SSD random read ~16–100 µs.
  • Round trip: same datacenter ~0.5 ms; California ↔ Netherlands ~150 ms.
  • 1 day = 86,400 s ≈ 10⁵ s, so 1M requests/day ≈ 12 QPS average.

During a network partition, a replicated system either refuses some requests (consistency) or serves possibly stale data (availability). PACELC adds: otherwise, every request trades latency against consistency.

  • Cloud Spanner multi-region SLA: 99.999% (~5 min/year): a CP system can still be highly available.
  • Inter-continent round trip ~70–150 ms: the floor for an EC write that must reach another region.
  • N=3 replicas: R=2, W=2 overlap (R + W > N); R=1, W=1 is the fast EL setting.

The contract for what a read may return on replicated data, from linearizable (behaves like one up-to-date copy) to eventual (converges someday). Stronger contracts cost latency and availability.

  • Quorum rule: R + W > N; the usual setting is N=3, W=2, R=2.
  • DynamoDB reads are eventually consistent by default; a strongly consistent read costs 2× the read capacity.
  • Amazon S3 has been strongly read-after-write consistent since December 2020.

Keep copies of the same data on several nodes for durability, availability and read scale. You choose who accepts writes (one, many or any node) and whether to wait for copies before acknowledging.

  • Amazon Aurora: up to 15 read replicas, with lag typically under 100 ms (AWS docs).
  • RDS Multi-AZ (one standby) failover typically completes in 1–2 minutes.
  • Patroni's default leader-lock TTL is 30 s: roughly how long a dead leader goes unnoticed before promotion starts.

Split data across nodes by a shard key, scaling writes and storage past one machine. The key decides load balance, which queries stay on one shard, and how painful rebalancing is.

  • Going from hash % N to % (N+1) moves ~N/(N+1) of keys (~91% at N=10); fixed partitions or consistent hashing move ~1/(N+1).
  • DynamoDB per-partition ceilings: 3,000 RCU, 1,000 WCU and 10 GB.
  • DynamoDB: 5 local and 20 global secondary indexes per table (default quota); GSIs are eventually consistent.

Place nodes and keys on the same hash ring and give each key to the next node clockwise, so adding or removing a node moves only ~1/N of the keys.

  • Growing from N to N+1 nodes: consistent hashing moves ~1/(N+1) of keys, % N moves ~N/(N+1). 10→11 is ~9% vs ~91%.
  • Rule of thumb: with V vnodes per node, load spread ≈ 1/√V, so 100 vnodes ≈ 10% standard deviation.
  • Cassandra: 256 vnodes per node by default before 4.0, 16 since 4.0 (paired with a smarter token allocator).

A cluster agrees on one ordered log of commands despite crashes: a leader replicates each entry and commits it once a majority stores it, so 2f+1 nodes survive f failures.

  • 2f+1 nodes tolerate f failures: 3→1, 5→2, 7→3. Even sizes add cost, not tolerance.
  • Rule of thumb: a commit costs one round trip to a majority plus an fsync, ~1–5 ms in one region and 50–200 ms across continents.
  • etcd defaults: 100 ms heartbeat, 1,000 ms election timeout, 2 GB storage quota.

Keep copies of expensive reads in faster storage; choose how writes reach the cache, bound staleness with TTLs or invalidation, and protect the origin from stampedes when hot keys expire.

  • Average latency = hit × cache + miss × origin: with 1 ms vs 50 ms, 90% hits → ~5.9 ms, 99% → ~1.5 ms.
  • Origin load scales with the miss rate: going from 90% to 99% hits cuts backend traffic 10×.
  • Latency ladder (Jeff Dean): RAM reference ~100 ns, same-datacenter round trip ~0.5 ms, disk seek ~10 ms.

A queue hands each message to one worker and deletes it on ack; a stream (Kafka) keeps an ordered, replayable log that many consumer groups read at their own offsets.

  • Kafka default retention: 7 days (log.retention.hours=168); compacted topics keep the latest value per key indefinitely.
  • SQS visibility timeout: 30 s default, 12 h max; message retention 4 days default, 14 days max.
  • Kinesis shard: 1 MB/s or 1,000 records/s in, 2 MB/s out.

Doing an operation N times has the same effect as doing it once. It's what makes retries and at-least-once delivery safe; get it with upserts, conditional writes or client-supplied idempotency keys.

  • Stripe keeps idempotency keys for at least 24 hours; reusing a key with different parameters returns an error.
  • HTTP (RFC 9110): GET, HEAD, OPTIONS, TRACE, PUT and DELETE are idempotent; POST is not, and PATCH isn't guaranteed to be.
  • SQS FIFO deduplicates by MessageDeduplicationId within a 5-minute window: dedup windows are always bounded.

Retry only transient errors, with exponential backoff plus jitter, within a deadline and a retry budget; when a dependency is clearly down, a circuit breaker fails fast or falls back instead of piling on.

  • Full jitter: sleep = random(0, min(cap, base × 2^attempt)) — AWS Architecture Blog.
  • Google SRE: at most 3 attempts per request, and a per-client budget keeping retries under 10% of requests.
  • Retries multiply across layers: 3 layers × 4 attempts each = 4³ = 64 calls on the bottom service.

Cap how much each client can consume per unit of time so one tenant can't starve the rest; for LLMs, meter tokens per minute, not just requests, and answer excess with 429 plus Retry-After.

  • HTTP 429 Too Many Requests is defined in RFC 6585; send Retry-After so clients know when to return.
  • A fixed window can admit up to 2× the limit in a burst straddling the boundary.
  • LLM providers limit RPM and TPM separately; Anthropic splits input (ITPM) and output (OTPM) tokens.

When demand exceeds capacity, bound every queue, push the slowdown back to callers that can wait, and reject the rest early and cheaply so the work you accept still finishes in time.

  • Queue wait ≈ depth ÷ service rate: 200 queued at 1,000 req/s is a 0.2 s wait.
  • Google SRE: for steady traffic, keep the queue at 50% or less of the thread pool size.
  • Google tags every request with one of four criticality levels: CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE.

Spread requests across replicas so none overloads and dead ones get skipped; for LLM serving, pick by live load (queue depth, KV-cache use) and prefix affinity, because request costs differ by orders of magnitude.

  • Placing n requests on n servers: one random pick gives a max load of ~log n / log log n; best of two random picks gives ~log log n.
  • Consistent hashing moves ~1/N of keys when one of N nodes leaves; hash mod N moves almost all of them.
  • Envoy outlier detection defaults: eject after 5 consecutive 5xx, 30 s base ejection, at most 10% of hosts.

An SLI measures what users feel, an SLO sets its target, and the gap to 100% is an error budget you spend on change; alert on how fast you burn it, not on raw errors.

  • Error budget per 30 days: 99% ≈ 7.2 h, 99.9% ≈ 43 min, 99.99% ≈ 4.3 min.
  • SRE Workbook defaults: page at 14.4× over 1 h (2% of budget) and 6× over 6 h (5%); ticket at 1× over 3 days (10%).
  • At a 14.4× burn rate, a 30-day budget is gone in ~2 days (30 / 14.4 ≈ 2.1).

Decide how much data you can lose (RPO) and how long you can be down (RTO), buy the cheapest strategy that meets both, and prove it with regular failover and restore tests.

  • AWS Well-Architected (checked Nov 2026): backup and restore = RPO hours, RTO up to a day; pilot light = RPO minutes, RTO tens of minutes.
  • Same source: warm standby = RPO seconds, RTO minutes; multi-site active-active pushes both toward zero.
  • Aurora Global Database (AWS, checked Nov 2026): asynchronous cross-region replication, typically under 1 s behind; a secondary is promoted in under a minute.

Pick the store from your access patterns, consistency needs and scale, not the label: Postgres by default (JSONB, pgvector), a specialized NoSQL store when one access pattern outgrows a single primary.

  • DynamoDB: 400 KB max item; each partition serves up to 3,000 RCU and 1,000 WCU per second.
  • MongoDB: 16 MB max document size.
  • pgvector indexes (HNSW, IVFFlat) support up to 2,000 dimensions for vector, 4,000 for halfvec.

A B-tree keeps keys sorted in pages updated in place: great for reads and ranges. An LSM tree buffers writes in memory and merges sorted files later: great for ingest. Every index taxes writes.

  • Page size: 8 KB in Postgres, 16 KB in InnoDB; with hundreds of keys per page, B-trees stay ~3–4 levels deep.
  • Bloom filter: ~10 bits per key gives ~1% false positives (RocksDB's classic setting).
  • Postgres covering indexes (INCLUDE) exist since v11; index-only scans need a vacuumed visibility map.

Event sourcing stores every change as an immutable event and derives state by replaying them; CQRS splits the write model from query-shaped read models. Great for audit and replay, costly in complexity and eventual consistency.

  • Kafka's default retention is 7 days (log.retention.hours=168): an event store needs retention set to forever.
  • Rule of thumb: snapshot a stream every ~100–1,000 events so loading never replays thousands.

Without distributed transactions, a saga chains local transactions and undoes completed steps with compensating actions on failure; the outbox makes each "update DB + publish event" atomic by writing both in one local transaction.

  • Sagas were introduced by Garcia-Molina and Salem in 1987, for long-lived transactions in a single database.
  • 2PC: two round trips with locks held throughout; a coordinator crash after PREPARE leaves participants blocked.
  • Postgres keeps WAL for an unconsumed replication slot indefinitely unless max_slot_wal_keep_size (PG 13+) caps it.

Start with a modular monolith; split out a service only when a team needs independent deploys or a part needs different scaling, because every split pays for autonomy with network hops and distributed data.

  • Jeff Dean's latency numbers: ~100 ns for a main-memory reference vs ~500 µs for a round trip within a datacenter, thousands of times more.
  • Availability compounds: 5 sequential dependencies at 99.9% each give ~99.5% end to end (0.999^5).
  • Amazon's two-pizza rule: a service is owned by a team small enough to feed with two pizzas.

Metrics tell you *that* something is wrong, traces *where*, logs *why*. Instrument with OpenTelemetry, alert on RED and USE, and keep high-cardinality detail on spans, not metric labels.

  • Series count = product of label values: 50 routes × 5 status codes × 20 pods = 5,000 series; add user_id with 1M users and it's 5 billion.
  • W3C traceparent carries a 16-byte trace-id and an 8-byte parent span-id.
  • Google SRE's four golden signals: latency, traffic, errors, saturation.

Serve many customers from one system by choosing, per layer, silo (dedicated), pool (shared with a tenant_id) or a bridge of both, trading cost per tenant against isolation, noisy neighbors and compliance.

  • Postgres RLS is skipped for superusers and BYPASSRLS roles, and for the table owner unless FORCE ROW LEVEL SECURITY is set.
  • HTTP 429 Too Many Requests (RFC 6585) with Retry-After is the standard reply to a tenant over its quota.
  • Postgres logical replication supports row filters since v15: copy one tenant's rows out of the pool with WHERE tenant_id = ....

REST for public resource APIs, gRPC for typed internal calls and streaming, an async contract (202 + status, webhooks, SSE) for anything slow; build in pagination, versioning and idempotency from day one.

  • RFC 9110: GET, HEAD, OPTIONS are safe; those plus PUT and DELETE are idempotent; POST is not.
  • Go async past ~30 s: AWS API Gateway's integration timeout defaults to 29 s and ALB's idle timeout to 60 s.
  • Stripe prunes idempotency keys after ≥24 h; a replay within that window returns the original result, even a 500.

A CDN caches your responses on servers near users, keyed by URL, so most requests never reach your origin; you control freshness with Cache-Control TTLs, versioned URLs and purges.

  • Origin load = requests × (1 − hit ratio): 95% hits → 5% reach the origin; 99% → 1%.
  • Fingerprinted assets: Cache-Control: public, max-age=31536000, immutable (one year).
  • CloudFront: first 1,000 invalidation paths a month free; a /* wildcard counts as one path (checked Nov 2026).

Store files as whole objects under bucket + key, over HTTP: virtually unlimited, very durable and cheap per GB, but you rewrite whole objects, pay per request, and keep metadata and queries in a database.

  • S3 Standard: designed for 11 nines (99.999999999%) durability, data in at least 3 AZs.
  • Multipart: parts of 5 MiB–5 GiB, at most 10,000; max object 50 TB since Dec 2025 (10,000 × 5 GiB).
  • Per partitioned prefix: at least 3,500 writes/s and 11,000 reads/s (AWS docs, Nov 2026); spread keys across prefixes to go higher.

Trade a small, bounded error for huge memory savings: a Bloom filter answers "seen it?" with no false negatives, HyperLogLog counts distinct items, and Count-Min estimates frequencies, in kilobytes instead of gigabytes.

  • Bloom: 1% false positives → ~9.6 bits/key and 7 hashes; 0.1% → ~14.4 bits/key and 10 hashes.
  • Bloom sizing: m = −n·ln p / (ln 2)² bits; optimal k = (m/n)·ln 2.
  • HyperLogLog standard error ≈ 1.04/√m; the paper counts beyond 10⁹ items at ~2% with 1.5 KB.

B-trees update pages in place for cheap reads; LSM-trees append and compact later for cheap writes, so choose by the amplification your workload can afford: write, read or space.

  • RocksDB tuning guide, 500 GB with 10× levels: write amp ~33, space amp ~1.14.
  • Leveled compaction keeps ~90% of data in the last level, so space amp stays near 1.1×.
  • Universal (size-tiered) compaction can temporarily double disk usage during a full compaction.

Machine clocks drift and jump, so timestamps can't order events across nodes; use logical clocks for causality (Lamport, vector) or hybrid clocks that also stay close to wall time.

  • NTP accuracy: ~1 ms or better on a LAN, tens of ms over the public internet.
  • Spanner (2012): TrueTime ε is a ~1–7 ms sawtooth, ~4 ms most of the time; assumed drift 200 µs/s.
  • 200 µs/s of drift = 6 ms after 30 s, ~17 s after a day without sync.

Every node periodically swaps what it knows with a few random peers, so membership and failure news reach the whole cluster in O(log N) rounds with no coordinator.

  • Cassandra: every second each node gossips with one random node, plus sometimes an unreachable node or a seed; it convicts peers with a phi accrual variant (phi_convict_threshold 8 by default).
  • HashiCorp memberlist LAN defaults (checked Nov 2026): gossip to 3 nodes every 200 ms, probe one node every 1 s, 3 indirect probes.
  • Dynamo paper (2007): each node contacts a random peer every second; gossiping the full membership works for a couple of hundred nodes.

A distributed lock is really a lease that expires, so a paused holder can outlive it; for correctness, take the lease from a consensus store or database and have storage reject stale fencing tokens.

  • Redis lock: SET key random NX PX 30000; release only if the value still matches (Lua script, or DELEX in Redis 8.4+).
  • Redlock: N = 5 independent Redis masters, a majority of 3 needed; ~5–50 ms per-node timeout for a 10 s lease.
  • Kleppmann (2016): GC pauses have lasted minutes, and one GitHub incident delayed packets ~90 s, far past typical TTLs.

Compute continuously over unbounded event streams: group events into windows by event time, use watermarks to decide when a window is complete, and checkpoint state so results survive failures exactly once.

  • Bounded-out-of-orderness watermark ≈ max event time seen − allowed delay (e.g. 30 s).
  • Flink exactly-once sinks use two-phase commit since Flink 1.4 (Dec 2017), committing on each checkpoint.
  • Kafka Streams: processing.guarantee=exactly_once_v2 (Kafka 3.0+, brokers 2.5+).

Push server events over the simplest channel that fits (polling for rare updates, SSE for one-way streams, WebSockets for two-way); at scale, the hard part is the stateful gateway tier and fan-out.

  • Browsers: 6 SSE connections per domain over HTTP/1.1, shared by all tabs; HTTP/2 negotiates streams (default 100) (MDN).
  • AWS ALB default idle timeout: 60 s. Send heartbeats more often or idle connections get cut.
  • Discord (2017): ~5M concurrent users; guilds up to 30k concurrent users; big-guild publishes took 900 ms–2.1 s before Manifold.

Map coordinates to cell ids so "what's near me?" becomes a lookup of a few cells plus an exact distance filter; size cells to the search radius and split cells that get hot.

  • Geohash at the equator: 5 chars ≈ 4.9 × 4.9 km, 6 ≈ 1.2 km × 609 m, 7 ≈ 153 × 152 m.
  • H3: 16 resolutions, each with ~7× more cells; res 8 ≈ 0.74 km² (edge ~0.53 km), res 9 ≈ 0.1 km².
  • An H3 k-ring holds 1 + 3k(k+1) hexagons: 7 for k=1, 19 for k=2.

Authentication proves who you are and authorization decides what you may do: log in with OIDC (auth code + PKCE), carry identity in short-lived tokens or sessions, and check permissions server-side on every request.

  • PKCE (RFC 7636, 2015): verifier of 43–128 chars; challenge = base64url(SHA-256(verifier)).
  • RFC 9700 (OAuth security BCP, Jan 2025): public clients MUST use PKCE; the password grant MUST NOT be used.
  • Amazon Cognito defaults (checked Nov 2026): access and ID tokens 1 hour, refresh tokens 30 days.

Encrypt data on the wire with TLS and on disk with keys held in a KMS, keep secrets in a vault as short-lived credentials, and store passwords only as slow, salted hashes.

  • TLS 1.3: RFC 8446 (August 2018), reissued with clarifications as RFC 9846 (July 2026). Static RSA key exchange removed, AEAD ciphers only, 1-RTT handshake; 0-RTT data can be replayed.
  • AWS KMS Encrypt takes at most 4,096 bytes, so bulk data needs a data key from GenerateDataKey.
  • AWS KMS automatic rotation (checked Nov 2026): every 365 days by default, configurable from 90 to 2,560 days; old key material is kept.

Ship changes to a small slice first, watch the metrics, then widen or roll back automatically; separate deploy from release with feature flags, and change schemas in backward-compatible expand/contract steps.

  • Google SRE: roughly 70% of outages are due to changes in a live system.
  • Kubernetes rolling update defaults: maxSurge 25% (rounded up), maxUnavailable 25% (rounded down).
  • SRE workbook example: a change failing 20% of requests behind a 5% canary costs ~1% of all requests.

System Design Classics

Give each long URL a short base62 key from a collision-free ID source, store key → URL in a sharded key-value store, serve redirects from cache, and log clicks asynchronously, off the redirect path.

  • Writes: 100M links/day (assumed) ÷ 86,400 s ≈ 1.2k/s; at 100:1 reads ≈ 116k redirects/s average.
  • Key space: 62^6 ≈ 56.8B, 62^7 ≈ 3.5T; at 100M/day, 6 characters last ~1.6 years, 7 last ~96 years.
  • Storage: 5 years ≈ 180B links × ~500 B ≈ ~90 TB before replication.

Enforce limits at the gateway with rules cached in memory and counters in a regional Redis updated by one atomic script; answer excess with 429 and Retry-After, and fail open if the limiter breaks.

  • Memory (assumed): 10M active keys × ~100 B per counter ≈ ~1 GB. Counter memory is rarely the constraint.
  • Throughput: 100k checks/s (assumed) is about one Redis instance's ~100k simple ops/s (rule of thumb): shard by client key.
  • Cloudflare (2017): its sliding-window counters wrongly allowed or limited only 0.003% of 400M requests.

Precompute each user's feed by pushing new post IDs into followers' cached lists, but pull posts from high-follower accounts at read time and merge; hydrate, rank, and page with cursors.

  • Reads: 300M DAU × 10 loads/day (assumed) = 3B/day ≈ 35k/s average, ~70k at a 2× peak.
  • Push: 150M posts/day × 200 followers (assumed) = 30B feed inserts/day ≈ 350k/s, 10× the read rate.
  • Feed cache: 300M users × 800 IDs × 8 B ≈ 1.9 TB of raw IDs; scores, Redis overhead and replicas multiply it.

Clients keep a WebSocket to a gateway; the chat service gives each message a per-conversation sequence, stores it, then delivers to online recipients or via push; clients dedup and resync from their last-seen sequence.

  • Traffic: 100M DAU × 50 messages/day (assumed) = 5B/day ≈ 58k msg/s average, ~120k at a 2× peak.
  • Storage: 5B × ~200 B ≈ 1 TB/day, ~365 TB/year before replication.
  • Connections: ~30M concurrent ÷ ~100k per gateway (both assumed) ≈ 300 gateways.

Services emit events; the notification service dedups, checks preferences and caps, renders per channel, and queues sends by priority to channel workers that call APNs, FCM, email and SMS providers with retries.

  • Volume: 100M users × 10 notifications/day (assumed) = 1B/day ≈ 12k/s average; campaigns spike far above.
  • Dedup keys: 1B/day × ~100 B ≈ 100 GB per day of TTL; a 7-day TTL ≈ 700 GB.
  • APNs: payload ≤ 4 KB (VoIP 5 KB); stores an undeliverable push up to 30 days.

Precompute the top-K completions per prefix offline from query logs, serve them from an in-memory index behind browser and CDN caches, and answer each keystroke well under 100 ms; merge a trending layer for freshness.

  • Traffic: 100M DAU × 10 searches × ~6 requests (assumed) = 6B/day ≈ 70k QPS, ~140k at peak.
  • Budget: ~100 ms keystroke-to-render feels instantaneous (Nielsen, 1993); the network uses most of it.
  • Memory: ~100M prefixes × top 10 × 4-byte IDs ≈ 4 GB plus keys (assumed): replicate, don't shard.

A URL frontier with one queue per host feeds fetch workers that obey robots.txt; new links pass a Bloom-filter seen-check, pages pass content dedup, and each host gets one request at a time.

  • Throughput: 1B pages/month ÷ ~2.6M s ≈ ~400 pages/s (assumption); plan ~800/s for a 2× peak.
  • Common Crawl, Aug 2026: 2.14B pages, 360 TiB uncompressed, ~185 KB per page.
  • Bloom filter: ~9.6 bits per item at 1% false positives, so 10B URLs ≈ 12 GB.

Place keys on a consistent-hash ring, replicate each to N nodes, and wait for W write and R read acks; versions resolve conflicts, while gossip, hinted handoff and Merkle-tree repair ride out failures.

  • Dynamo (2007): common (N, R, W) = (3, 2, 2); example SLA 300 ms at p99.9 for 500 requests/s.
  • Divergence is rare: 99.94% of shopping-cart reads saw exactly one version over 24 h.
  • Dynamo truncates vector clocks at ~10 (node, counter) pairs; Cassandra stores hints only for a node's first 3 h down (default).

Partition keys across memory-only nodes by hash slot or consistent hashing, evict by LRU or LFU at a memory limit, replicate asynchronously for failover, and protect the database from hot keys and cold nodes.

  • Redis Cluster: 16,384 slots, slot = CRC16(key) mod 16384; suggested maximum of ~1,000 nodes.
  • Memcached defaults: 64 MB of memory, 1 MB max item, 4 threads, port 11211; keys are limited to 250 bytes.
  • Redis defaults: no memory limit, noeviction, and 5 keys sampled per eviction.

Upload the original once in resumable parts, transcode it in parallel chunks into a bitrate ladder of short segments, and serve them from a CDN; the player picks a quality per segment.

  • Egress: assume 100M views/day × 5 min × ~3 Mbps → ~11 PB/day, ~1 Tbps average.
  • Apple's example H.264 ladder: 145 kbps (416×234) to 7,800 kbps (1080p); 9 rungs sum ~25.6 Mbps.
  • Apple HLS spec: ~6 s target segment duration, a keyframe every 2 s.

Drivers stream GPS every few seconds into an in-memory index of H3 cells; a request searches nearby cells, ranks drivers by road ETA, claims one atomically, and a trip state machine runs to payment.

  • Assume 1M online drivers × 1 ping / 4 s ≈ 250k location writes/s at peak.
  • H3 average cell: res 8 ≈ 0.74 km² (edge ~530 m); res 9 ≈ 0.105 km² (edge ~200 m).
  • A hex disk of radius k covers 1 + 3k(k+1) cells: 7 for k = 1, 19 for k = 2.

Index mostly static businesses by geohash cell; a search reads the user's cell plus its 8 neighbors from cache or read replicas, filters by exact distance, and widens the cell when results are few.

  • Load (assumed): 100M daily users × 5 searches ÷ 86,400 s ≈ ~5.8k searches/s on average.
  • Geohash cells at the equator: 4 characters ≈ 39.1 × 19.5 km, 5 ≈ 4.9 × 4.9 km, 6 ≈ 1.2 km × 609 m.
  • Each geohash character adds 5 bits: one character less is a 32× larger cell.

Record the payment intent, call the PSP with an idempotency key, and post the outcome as balanced double-entry ledger entries; webhooks and daily reconciliation against PSP reports catch whatever the synchronous path missed.

  • Assume 10M payments/day ≈ ~115/s average; plan ~10× for peak sales events.
  • Stripe API v1 (Nov 2026): idempotency keys up to 255 chars, prunable after ≥ 24 h.
  • Stripe retries webhooks for up to 3 days in live mode, with no ordering guarantee (Nov 2026).

Move money between accounts on different shards as an idempotent debit-then-credit saga recorded in a double-entry ledger; the append-only log makes every balance reproducible, and reconciliation proves no money was created or lost.

  • Sizing (assumed): 10k transfers/s × 2 local writes ÷ ~1k writes/s per node ≈ 20 shards.
  • With S shards, a transfer stays on one shard with probability 1/S: 20 shards means ~95% cross-shard.
  • Ledger volume: 4 entries per transfer, so 10k transfers/s ≈ 40k entries/s at peak.

Hold seats with one atomic conditional write that expires after ~10 minutes, charge with an idempotency key, then confirm only if the hold is still yours; a virtual waiting room meters the spike.

  • Demand (assumed): 2M fans for 50k seats = 40 fans per seat; at ~4 seats per order, ~99% leave without tickets.
  • Orders: 50k seats ÷ ~4 per order ≈ 12.5k orders; selling out in 10 min is only ~21 orders/s.
  • Waiting room (assumed 2k admits/min): the last of 2M fans would wait ~1,000 min (~17 h), so announce sold-out early.

One session server per document orders every edit, transforms or merges concurrent edits (OT or CRDT), appends them to an operation log and broadcasts them; cursors travel on a separate, ephemeral presence channel.

  • Load (assumed): 1M concurrent editors × ~1 batched op/s ≈ 1M ops/s in; at ~3 editors per doc, ~2M broadcasts/s out.
  • Log volume (assumed ~100 B per op): 1M ops/s ≈ 100 MB/s at peak; compact old ops into snapshots.
  • Snapshot every ~1,000 ops (assumed): opening a doc replays at most ~1,000 ops on top of it.

Store each job's next run time; sharded schedulers claim due jobs and enqueue a run with a deterministic id; workers execute under heartbeated leases; delivery is at-least-once, so every job must be idempotent.

  • Load (assumed): 100M runs/day ≈ 1.2k/s; if 20% fire in the first minute of each hour, that minute sees ~14k/s (~12×).
  • Lease (assumed): 30 s with a heartbeat every 10 s; a crashed worker's run restarts within ~30 s.
  • SQS visibility timeout, the same lease idea: 30 s by default, at most 12 h (checked Nov 2026).

Split files into hashed blocks, upload only blocks the server lacks, commit the file as a hash list with a version check, and tell other devices to pull changes since their cursor.

  • Commits (assumed): 50M DAU × 10 changes/day = 500M/day ≈ 5.8k/s average, ~12k/s at a 2× peak.
  • Upload (assumed ~200 KB of new data per change after dedup): 500M × 200 KB ≈ 100 TB/day into block storage.
  • Dropbox: 4 MB blocks hashed with SHA-256 (2014); Magic Pocket stored multiple exabytes (2016).

Buffer samples through an ingest pipeline into a compressed time-series store sharded by series, downsample old data for long ranges, cap label cardinality, and evaluate alert rules on recent data, independently of what they watch.

  • Ingest (assumed): 10k hosts × 1,000 series ÷ 15 s ≈ 670k samples/s.
  • Storage: 670k/s × 86,400 s × ~1.37 B ≈ 79 GB/day raw, ~29 TB/year before retention and downsampling.
  • Gorilla (VLDB 2015): 16 B to ~1.37 B per point (12×); ~96% of timestamps compress to a single bit.

Store each topic as partitioned append-only logs, replicate every partition from a leader to in-sync followers, acknowledge once they have the write, and let consumer groups pull by offset and commit their own position.

  • Assumed load: 1M messages/s × 1 KB ≈ 1 GB/s ≈ 86 TB/day; 7 days × 3 replicas ≈ 1.8 PB.
  • Kafka defaults (4.4 docs, checked Nov 2026): 1 GiB segments, 7-day retention; acks=all and the idempotent producer are defaults since 3.0 (Sept 2021, KIP-679).
  • A follower leaves the ISR after 30 s behind the leader (replica.lag.time.max.ms).

Log clicks to Kafka, drop duplicates by click id, count per ad per minute by event time with exactly-once output into an OLAP store, and reconcile against a batch recount of the raw log.

  • Assumed: 1B clicks/day ÷ 86,400 s ≈ 11.6k/s average, ~58k/s at a 5× peak.
  • Raw log: 1B × ~0.5 KB (assumed) ≈ 500 GB/day.
  • Dedupe state: ~42M click ids per hour of TTL (1B ÷ 24).

Count events per item in time buckets, keep a size-K heap over the counts, and sum buckets for sliding windows; switch to a count-min sketch when exact per-item counters stop fitting in memory.

  • Assumed: 1B events/hour ≈ 278k/s over 50M distinct items.
  • Space-Saving with m counters keeps every item above N/m occurrences; a count is at most N/m too high.
  • Count-min: w = ⌈e/ε⌉, d = ⌈ln(1/δ)⌉. With ε = 0.00001 and δ = 1%: 271,829 × 5 counters ≈ 11 MB at 8 B each.

Keep scores in a Redis sorted set: score updates and rank lookups are O(log N), the top 10 is one range read, and the set is a view rebuilt from the durable score store.

  • ZADD, ZINCRBY, ZREVRANK, ZCOUNT: O(log N). ZSCORE: O(1). A range of M: O(log N + M).
  • Assumed load: 5M DAU × 10 matches = 50M updates/day ≈ 580/s average, ~3k/s at peak.
  • Memory: 50M members × ~100 B (assumed) ≈ 5 GB, which fits one node.

Coding Interview Patterns

Big-O says how time or memory grows with input size, ignoring constants: before coding, name n, state time and space, and check them against the input limits.

  • ~1 s budget (CPH): n ≤ 20 → O(2ⁿ); n ≤ 500 → O(n³); n ≤ 5,000 → O(n²); n ≤ 10⁶ → O(n log n) or O(n).
  • A modern CPU runs some hundreds of millions of simple operations per second; O(n²) at n = 10⁵ is 10¹⁰ steps.
  • log₂(10⁶) ≈ 20 and log₂(10⁹) ≈ 30: a log factor is cheap.

A hash map gives O(1) average lookup by key, so "have I seen X?", "how many X?" and, with prefix sums, "how many subarrays sum to k?" each take one O(n) pass.

  • Python dict/set: get, set, delete and in are O(1) average, O(n) worst case when keys collide.
  • Python salts str and bytes hashes per process by default (since 3.3) to block hash-flooding denial of service.
  • Java 8 HashMap turns crowded buckets into balanced trees: worst case O(log n) instead of O(n) for comparable keys.

Precompute running totals once in O(n) and any range sum is one subtraction, O(1); the mirror trick, a difference array, makes each range update O(1).

  • Build O(n), query O(1): q queries cost O(n + q) instead of O(n·q).
  • 2D: build in O(rows × cols); any rectangle sum is 4 lookups.
  • Difference array: O(1) per range update plus one O(n) pass: O(n + u) for u updates.

Move two indexes through a sorted array, string or linked list so every step discards candidates for good: O(n) time, O(1) space, where brute force checks all O(n²) pairs.

  • Pair sum on sorted input: O(n) time, O(1) space; O(n log n) if you sort first.
  • 3Sum: O(n²) with sort plus two pointers, versus O(n³) brute force.
  • Floyd cycle detection: O(n) time and O(1) space, versus O(n) space for a visited set.

Keep a contiguous window over an array or string and update its state as the edges move; each element enters and leaves once, so subarray and substring scans drop from O(n²) to O(n).

  • O(n) time: right moves n times and left at most n times in total.
  • Space O(k) for window counts, k = alphabet size or distinct values (26 for lowercase letters).
  • Brute force: O(n²) windows, O(n³) if each is rescanned.

Halve a sorted range each step to find a value, or the first point where a monotonic yes/no predicate flips, in O(log n) checks: ~30 even for a 10⁹-wide answer space.

  • log₂(10⁶) ≈ 20 and log₂(10⁹) ≈ 30 iterations.
  • Search on the answer costs O(log(range) × cost of one check), e.g. O(n log(sum)).
  • The (low + high) / 2 overflow bug sat in the JDK's binary search ~9 years before it was reported (Bloch, 2006).

A linked list gives up index access to get O(1) insert and delete at a known node; interview problems are pointer surgery with three tools: a dummy head, in-place reversal and fast/slow pointers.

  • Access and search O(n); insert or delete O(1) once you hold the previous node (any node, if doubly linked).
  • Reverse, find the middle, detect a cycle: O(n) time, O(1) space.
  • Merge two sorted lists of n and m nodes: O(n + m) time, O(1) extra space.

Most tree problems are one traversal: a DFS where each node combines what its children return, or a BFS level by level; in a BST, inorder visits the keys in sorted order.

  • Traversal: O(n) time. Space: O(h) for DFS (h = height), O(w) for BFS (w = widest level, up to ~n/2).
  • Height: ~log₂ n when balanced (~20 for 10⁶ nodes), n when skewed like a linked list.
  • BST search, insert, delete: O(h), so O(log n) balanced and O(n) skewed.

A stack holds the items still waiting for an answer; a monotonic stack pops every item the new one beats, so 'next greater or smaller' problems drop from O(n²) to O(n).

  • Time O(n): each index is pushed once and popped at most once (≤ 2n operations).
  • Space O(n) worst case: a strictly decreasing input never pops.
  • Sliding window max: O(n) with a deque, O(n log n) with a lazy-deletion heap, O(n·k) brute force.

A heap returns the smallest (or largest) item in O(1) and inserts or removes in O(log n); a size-K heap gives top-K in O(n log K) without sorting everything.

  • Push and pop O(log n); peek O(1); heapify O(n).
  • Top-K: O(n log K) time, O(K) space. Full sort: O(n log n) time, O(n) space.
  • K-way merge of N total items from k lists: O(N log k).

Sort intervals by start, then sweep left to right comparing each one with the last kept interval; for 'how many at once', sweep +1/−1 start and end events instead.

  • Merge, meeting rooms, scheduling: O(n log n) for the sort, then O(n).
  • Insert into an already sorted, disjoint list: O(n), no sort.
  • Meeting rooms: 2n events; the answer is the peak of the running sum.

BFS explores level by level with a queue and finds shortest paths when every edge costs the same; DFS goes deep with a stack or recursion; with a visited set, both are O(V + E).

  • Time O(V + E) with adjacency lists; O(V²) with an adjacency matrix.
  • Grid R × C: R·C nodes and ≤ 4·R·C neighbor checks.
  • Space O(V) for the visited set; the BFS queue holds up to the widest level.

Order a directed graph so every edge points forward: repeatedly take a node with no remaining prerequisites (Kahn), or reverse the DFS finish order; nodes left over mean a cycle.

  • Time O(V + E); space O(V) for in-degrees and the queue.
  • Course schedule with n courses and p prerequisite pairs: O(n + p).
  • Longest path: O(V + E) on a DAG via topological order plus DP; NP-hard on general graphs.

Track groups as trees with one root each: `find` returns the root, `union` links two roots, and with path compression plus union by rank both run in near-constant amortized time.

  • Both optimizations: amortized O(α(n)) per operation; α(n) ≤ 4 for any realistic n (Tarjan, 1975).
  • Union by rank alone: O(log n) per find; rank never exceeds ⌊log₂ n⌋.
  • Kruskal's MST: O(E log E), dominated by sorting the edges.

Choose by edge weights: BFS when all edges cost the same, Dijkstra with a min-heap when weights are non-negative, Bellman-Ford when some are negative or you must detect a negative cycle.

  • BFS: O(V + E). Dijkstra with a binary heap: O((V + E) log V).
  • Bellman-Ford: O(V·E), V − 1 rounds plus one round to detect a negative cycle.
  • DAG shortest paths: O(V + E) in topological order, negative weights allowed.

When the best answer is built from best answers to smaller subproblems, and those subproblems repeat, solve each one once and store it: exponential recursion becomes polynomial.

  • Time = states × work per state: LCS and edit distance O(m·n); 0/1 knapsack O(n·W).
  • Fibonacci: naive recursion ~O(2ⁿ) calls; memoized O(n).
  • Two rolling rows cut edit distance memory from O(m·n) to O(min(m, n)).

Take the locally best choice at each step and never undo it; it is correct only when you can prove, usually with an exchange argument, that the choice never rules out an optimal solution.

  • Typical cost: O(n log n) for the sort, then O(n). Jump game: O(n) time, O(1) space.
  • Coins {1, 3, 4}, amount 6: greedy uses 3 coins (4 + 1 + 1); the optimum is 2 (3 + 3).
  • US coins without the nickel, {25, 10, 1}, for 40¢: greedy uses 7 coins; the optimum is 4 (4 × 10).

Build a candidate one choice at a time, recurse, then undo the choice, abandoning any partial candidate that can't lead to a valid answer: the way to enumerate subsets, permutations and constraint puzzles.

  • Subsets: 2ⁿ results, O(n·2ⁿ) with copying; n = 20 → 1,048,576 subsets.
  • Permutations: n! results; 10! = 3,628,800.
  • Combinations: C(n, k) = n! / (k!(n − k)!) results.

A tree where each edge is a character and each path from the root spells a prefix, so insert, lookup and "any word starting with...?" cost O(key length), however many words are stored.

  • insert, search, startsWith: O(L) for a key of length L, independent of the number of keys.
  • Space: O(total characters) in the worst case, one node per distinct prefix.
  • Array children: O(1) child lookup, but one slot per alphabet letter in every node (26 for a–z).

In a "design a class" round no single structure makes every operation O(1), so you compose two: a hash map to find things plus a list, linked list or stack that keeps the order.

  • LRU cache: get and put in O(1) average; space O(capacity).
  • Min stack: push, pop, top and getMin in O(1); O(n) extra space for the stored minimums.
  • Random set: insert, remove and getRandom in O(1) average (hash map).

Staff/Principal Leadership

Staff means you're measured at multi-team scope: you choose which problems matter, set technical direction, and make other engineers more effective, not just ship more code yourself.

  • Larson's archetypes: 4 — Tech Lead, Architect, Solver, Right Hand.
  • Rule of thumb: lead at most ~2–3 problems yourself at once; support the rest.

A strategy is a diagnosis of the real problem, a guiding policy that rules options in and out, and a few coherent actions, grounded in real design docs rather than a wishlist of goals.

  • Rumelt's kernel has 3 parts: diagnosis, guiding policy, coherent actions.
  • Larson's recipe: 5 design docs → 1 strategy; 5 strategies, forecast 2 years out → 1 vision.
  • Rule of thumb: 2–4 pages gets read; the kernel itself should fit on one.

A design doc is a written proposal reviewed before you build: context, goals and non-goals, the design, real alternatives and trade-offs, so the expensive arguments happen on paper, not in production.

  • Rule of thumb: 2–6 pages; if it needs 20, split it into several docs.
  • Rule of thumb: about a week of async review, then a short decision meeting only if needed.
  • Rule of thumb: at least two real alternatives, one of them "do nothing".

An ADR is a one-page record of one significant decision (context, decision, consequences) kept in the repo and never edited after acceptance, only superseded, so future engineers know why.

  • Nygard (2011): 5 sections — title, status, context, decision, consequences.
  • Rule of thumb: 1–2 pages; anything longer is exploration that belongs in a design doc.

Match process to reversibility: one-way doors (costly to undo) get slow, deliberate analysis; two-way doors get decided fast by a small group. Good architecture turns one-way doors into two-way ones.

  • Bezos (2016): decide with ~70% of the information you wish you had; waiting for 90% is usually too slow.
  • Type 1 / Type 2 decisions: Amazon's 2015 shareholder letter.

Build only what differentiates you or what no vendor can do under your constraints; buy the rest. In AI that usually means buy the models, build the evals, data and integration.

  • Rule of thumb: compare TCO over ~3 years, including the people who run it, not just the first build.
  • Rule of thumb: run the POC on a few hundred of your real cases, identical for every option.

Staff engineers move decisions through trust, not rank: learn what each stakeholder is measured on, pre-wire before the meeting, write it down, bring evidence, and give the credit away.

  • Rule of thumb: no decision-maker hears your proposal for the first time in the decision meeting.
  • Rule of thumb: the proposal fits in 1–2 pages; details go in an appendix.

Lead with the recommendation, translate it into business impact, show two or three options with cost, risk and time, quantify with honest ranges, and fit it on one page.

  • Translate rates into counts: 95% accuracy at 10,000 requests a day is ~500 wrong answers a day.
  • Rule of thumb: one page, 2–3 options, one explicit ask, one decision date.
  • Rule of thumb: the first sentence must still work if it's the only one read.

Technical debt is the extra cost every future change pays for a past shortcut. Prioritize it by the interest it charges — slower delivery, incidents, failed changes — not by ugliness.

  • DORA's four keys: deployment frequency, change lead time, change fail rate, failed deployment recovery time (DORA's current name for time to restore / MTTR); a fifth, deployment rework rate, was added later.
  • Rule of thumb: interest ≈ extra time per change × changes per month in that area.
  • Rule of thumb: reserve a fixed slice of every cycle (often 10–20%) for debt and maintenance.

Pick use cases by value × feasibility × risk, start internal and low-risk, build shared platform pieces once, govern explicitly, and measure ROI against a baseline — or pilots never reach production.

  • Rule of thumb: build a shared platform capability when the second or third team needs it, not before.
  • Rule of thumb: no pilot starts without an owner, a baseline, an eval set and kill criteria.
  • Rule of thumb: score 1–5 per axis and multiply, so one weak axis sinks the total.

Treat AI coding tools as an engineering-system change, not a license purchase: keep review and security gates, make repos agent-friendly, measure delivery and quality against a control, and expand where data shows gains.

  • METR RCT (Jul 2025): 16 experienced OSS developers, 246 tasks, 19% slower with AI; they predicted 24% faster and afterwards believed 20% faster.
  • GitHub RCT (Peng et al., 2023): the Copilot group finished an HTTP-server task 55.8% faster.
  • DORA 2025 (~5,000 respondents): 90% use AI at work, median ~2 h/day; >80% report higher productivity; 30% trust AI little or not at all.

Make AI spend visible, owned and predictable: tag every call at the gateway by team, feature and customer, track cost per business outcome, and pull the cheap levers before buying commitments.

  • Batch APIs (OpenAI, Anthropic) bill asynchronous jobs at ~50% of the synchronous price, with up to 24 h turnaround.
  • Output tokens list at several times the input price on major APIs (4× and 5× are common), so output caps pay off early.
  • Forecast: monthly cost ≈ active users × calls per user × tokens per call × blended price per token.

During an incident, one commander coordinates, roles are split, and you mitigate before you diagnose; afterwards, a blameless postmortem turns the timeline into owned action items that fix the system, not the person.

  • Rule of thumb: SEV1 stakeholder updates every 15–30 min, SEV2 every hour, even when the update is "no change".
  • Rule of thumb: postmortem draft within about a week, while memory and logs are fresh.
  • Track time to detect, time to mitigate and time to resolve separately; mitigation is the one users feel.

Mentoring gives advice, coaching asks questions until they find the answer, sponsorship spends your credibility to get them the opportunity. Staff engineers do all three, and scale them through writing, reviews and delegated ownership.

  • Rule of thumb: delegate the problem, keep review of the one-way doors; agree which ones before work starts.
  • Rule of thumb: give SBI feedback within days, while the situation is still concrete for both of you.

Answer every "tell me about a time" with a 2–3 minute STAR story: Situation, Task, Action, Result, plus what you learned. Prepare 8–10 stories mapped to Staff competencies, say "I", and quantify the result.

  • Rule of thumb: 2–3 minutes per story, with Situation + Task under ~30 seconds.
  • Story bank: 8–10 stories, each tagged with 2–3 competencies, including at least one real failure and one conflict.
  • Rule of thumb: every Result carries a number, or a concrete before/after when no metric exists.

Lead a cross-team project by owning the outcome, not the tickets: scope with non-goals, attack the biggest risk first, give each workstream one owner, report status that names risks, and stay until it's finished.

  • Rule of thumb (Orosz): milestones small enough to finish in a few weeks; split longer ones.
  • Rule of thumb (Orosz): a written status update every week and a demo every week or two.
  • RACI and DACI both allow exactly one Accountable (or Approver) per decision.

Estimate as a range with a confidence level, never a bare date: break the work down, spike the biggest unknown, add an explicit buffer, and re-plan at each milestone, sharing slips early.

  • Cone of uncertainty: at the initial concept, actual effort can land ~0.25×–4× the estimate (Boehm, 1981; McConnell).
  • PERT expected value: (optimistic + 4 × likely + pessimistic) ÷ 6; long late tails pull it above "likely".
  • Evidence-Based Scheduling (Spolsky, 2007): tasks of 16 hours or less; simulate 100 futures from past estimate/actual ratios.

Measure the delivery system, not individuals: read DORA's throughput and instability metrics together, per service and as trends, alongside surveys and outcomes, and never make them targets (Goodhart's law).

  • DORA 2024 elite cluster: on-demand deploys, lead time < 1 day, change fail rate ~5%, recovery < 1 hour.
  • Clusters were re-derived from survey data each year; DORA 2025 replaced them with seven team archetypes.
  • Five metrics since 2024 (rework rate added); in 2023, MTTR became failed deployment recovery time.

Approve a change once it clearly improves code health, not when it's perfect: keep changes small, respond within a business day, review design before style, and use comments to teach.

  • Google's guide: respond within one business day at most.
  • Google's guide: ~100 lines is usually a reasonable change; ~1,000 is usually too large.
  • Google study (2018, 9M changes): median change of 24 lines, median of 1 reviewer, median review latency under 4 hours.

Ask every candidate the same role-relevant questions, score answers on an anchored rubric with written evidence before the debrief, and calibrate interviewers: structure predicts performance better than gut feel and reduces bias.

  • Sackett et al. (2022) validity: structured interviews ~0.42, work samples ~0.33, unstructured interviews ~0.19.
  • The older, still-quoted Schmidt & Hunter (1998) figures: structured 0.51, unstructured 0.38.
  • Google re:Work: rejected candidates with a structured interview were 35% happier with the process.

Rank work by what it's worth per unit of effort and by what waiting costs, drop what doesn't serve the strategy, and say no by naming the trade-off: yes to this means that slips.

  • CD3 = cost of delay ÷ duration; the highest score goes first.
  • Black Swan Farming's worked example: CD3 order cut total delay cost 61% vs first-in-first-out ($69k → $27k).
  • RICE scales (Intercom, 2018): impact 3 / 2 / 1 / 0.5 / 0.25; confidence 100% / 80% / 50%; effort in person-months.