Numbers to have at hand
LLM Fundamentals
- English: ~4 characters or ~0.75 words per token; 100 tokens ≈ 75 words. Tokens & tokenization
- Vocabulary sizes: GPT-2 50,257; cl100k_base ~100k; o200k_base ~200k; Llama 3 128,256. Tokens & tokenization
- Spanish typically needs ~20–50% more tokens than English for the same text, depending on the tokenizer. Tokens & tokenization
- Across languages the same text can take up to ~15× more tokens (Petrov et al., 2023). Tokens & tokenization
- Output tokens are commonly priced ~4–8× input tokens. Tokens & tokenization
- Common dims: 384 (all-MiniLM-L6-v2), 768 (BERT-base class), 1,024, 1,536 and 3,072 (OpenAI text-embedding-3-small / -large). Embeddings
- Storage: dims × 4 bytes per float32 vector; 1M × 1,536 ≈ 6.1 GB. int8 is 4× smaller, binary 32×. Embeddings
- Unit vectors: cosine = dot product, and L2² = 2 − 2·cosine, so all three rank identically. Embeddings
- Max input: text-embedding-3 takes 8,192 tokens; all-MiniLM-L6-v2 truncates at 256 word pieces. Embeddings
- Params ≈ 12 × layers × d_model² for a classic block; GPT-3: 12 × 96 × 12,288² ≈ 174B. Transformer architecture
- Llama 3 8B: 32 layers, d_model 4,096, 32 query / 8 KV heads, MLP width 14,336, vocab 128,256. Transformer architecture
- MLPs hold ~2/3 of each block classically; ~81% in Llama 3 8B (SwiGLU + GQA), ~70% of all params. Transformer architecture
- Compute: ~2 × params FLOPs per token forward; ~6 × params per token to train. Transformer architecture
- Weights memory = params × bytes per param: 8B in bf16 ≈ 16 GB. Transformer architecture
- Score matrix per head per layer: n² entries; 32k tokens ≈ 1.07B entries. Self-attention
- Doubling context ≈ 4× attention FLOPs but only 2× KV cache. Self-attention
- KV cache per token = 2 × layers × KV heads × head_dim × bytes; Llama 3 8B in bf16 ≈ 128 KiB. Self-attention
- GQA in Llama 3 8B: 32 query heads share 8 K/V heads, a 4× smaller cache than MHA. Self-attention
- Typical head dimension: 64–128. Self-attention
- 128k tokens ≈ ~96k English words ≈ ~300 pages. Context window
- 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+). Context window
- Output caps are separate and smaller: 16,384 tokens for GPT-4o, 65,536 for Gemini 2.5 Pro. Context window
- RULER (2024): of models claiming 32k+ context, only about half held up at 32k. Context window
- Chat re-sends history every turn, so session input tokens grow ~quadratically with turn count. Context window
- 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). Decoding & sampling (temperature, top-p)
- Common truncation settings: top_p 0.9–0.95; min_p 0.05–0.1. Decoding & sampling (temperature, top-p)
- Thinking Machines: 1,000 runs of one prompt at T=0 on Qwen3-235B gave 80 distinct completions; batch-invariant kernels made them identical. Decoding & sampling (temperature, top-p)
- Vocabulary scored at every step: ~128k tokens (Llama 3) to ~200k (OpenAI o200k). Decoding & sampling (temperature, top-p)
- Per token: 2 × layers × kv_heads × head_dim × bytes per value. KV cache
- Llama-3.1-8B fp16: 128 KiB/token → ~16 GiB at 128k tokens, about the size of its weights. KV cache
- Llama-3.1-70B fp16: 320 KiB/token → ~40 GiB per 128k-token sequence. KV cache
- GQA with 8 KV heads instead of 32: 4× smaller cache; FP8 KV: another 2×. KV cache
- vLLM paper: earlier servers used only ~20–38% of KV memory for real tokens; PagedAttention wastes under 4%. KV cache
- Pretraining data: Llama 3 ~15T tokens; DeepSeek-V3 14.8T. How LLMs are trained
- Llama 3.1 405B: ~3.8×10^25 FLOPs on up to 16k H100 GPUs. How LLMs are trained
- DeepSeek-V3: ~2.79M H800 GPU-hours in total, only ~5K of them post-training. How LLMs are trained
- InstructGPT: labelers preferred the 1.3B instruct model over the 175B GPT-3 base. How LLMs are trained
- LIMA: 1,000 curated SFT examples turned a 65B base model into a strong assistant. How LLMs are trained
- Training ≈ 6·N·D FLOPs; inference ≈ 2·N FLOPs per token. Scaling laws & Chinchilla
- Chinchilla-optimal: ~20 tokens per parameter (70B on 1.4T tokens). Scaling laws & Chinchilla
- GPT-3: ~1.7 tokens/param; Llama 3 8B: ~1,875 tokens/param (15T tokens). Scaling laws & Chinchilla
- Llama 3.1 405B: ~3.8×10^25 FLOPs on 15.6T tokens. Scaling laws & Chinchilla
- Kaplan's loss-vs-compute exponent is ~0.05: 10× more compute cuts loss by only ~11%. Scaling laws & Chinchilla
- Mixtral 8x7B: ~47B total, ~13B active (top-2 of 8 experts). Mixture of Experts (MoE)
- DeepSeek-V3: 671B total, 37B active (8 of 256 routed experts + 1 shared). Mixture of Experts (MoE)
- Qwen3-235B-A22B: 235B total, 22B active. Mixture of Experts (MoE)
- gpt-oss-120b: ~117B total, ~5.1B active; fits one 80 GB GPU with MXFP4 weights. Mixture of Experts (MoE)
- Compute per token ≈ 2 × active params; weight memory ≈ total params × bytes per param. Mixture of Experts (MoE)
- o1 on AIME 2024: 74% pass@1 vs 12% for GPT-4o; 83% with 64-sample consensus. Reasoning models & test-time compute
- DeepSeek-R1-Zero, pure RL: AIME 2024 pass@1 from 15.6% to 71.0%; R1 reached 79.8%. Reasoning models & test-time compute
- Anthropic manual extended thinking: minimum
budget_tokensis 1,024 (Claude 4.7+ uses adaptive thinking +effortinstead). Reasoning models & test-time compute - OpenAI suggests reserving ≥25,000 output tokens for reasoning + answer when you start. Reasoning models & test-time compute
- SimpleQA (OpenAI): gpt-5-thinking-mini abstains 52%, errs 26%; o4-mini abstains 1%, errs 75%, at similar accuracy (22% vs 24%). Hallucinations: why they happen
- Kalai et al.: if ~20% of facts like birthdays appear once in training, expect ≥~20% hallucination on them. Hallucinations: why they happen
- Mata v. Avianca (2023): 6 invented case citations, $5,000 sanction. Hallucinations: why they happen
- LLaVA-1.5: one 336×336 image → 576 visual tokens (24×24 patches of 14 px). Multimodal models
- Claude (2026 docs): 1 token per 28×28 px patch; max 1,568 per image, 4,784 on Claude 4.7+. Multimodal models
- GPT-4o: 85 tokens at low detail; a 1024×1024 image at high detail ≈ 765 tokens. Multimodal models
- Gemini 2.x: 258 tokens for an image ≤384 px per side (larger ones are tiled); audio ≈ 32 tokens/s. Multimodal models
- GPT-4o voice: ~320 ms average reply vs 2.8–5.4 s for the earlier ASR→LLM→TTS Voice Mode. Multimodal models
- BERT-base 110M / BERT-large 340M params; pretraining masks 15% of tokens. Encoder vs decoder models (BERT vs GPT)
- DistilBERT: 40% smaller, 60% faster, keeps ~97% of BERT's language understanding. Encoder vs decoder models (BERT vs GPT)
- ModernBERT (Dec 2024): 8,192-token context, 149M (base) / 395M (large) params. Encoder vs decoder models (BERT vs GPT)
- all-MiniLM-L6-v2: 22M params, 384-dim embeddings, still a common baseline. Encoder vs decoder models (BERT vs GPT)
- FrugalGPT: LLM cascades matched GPT-4 quality with up to 98% lower cost on its benchmarks. Choosing a model
- 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). Choosing a model
- 200 eval cases at ~90% accuracy → ±~4 points 95% confidence interval: smaller gaps are noise. Choosing a model
- Llama community license: services above 700M monthly active users need a separate license from Meta. Choosing a model
Prompting & Context Engineering
- Anthropic: long docs (~20K+ tokens) on top and the query at the end gave up to ~30% better responses on complex multi-document inputs. Anatomy of a prompt
- OpenAI GPT-4.1 guide: instructions both above and below long context beat either alone; if only once, put them above. Anatomy of a prompt
- Anthropic cache reads bill at 10% of the base input price (5% on Opus/Sonnet 5.5, late 2026), for an identical prefix only. Anatomy of a prompt
- OpenAI caches prompts automatically from 1,024 tokens, also prefix-only. Anatomy of a prompt
- Start with 3–5 diverse examples (Anthropic's guidance); add more only if your eval improves. Zero-shot vs few-shot prompting
- Zhao et al. 2021: prompt format, example choice and order alone swung GPT-3 from near chance to near state-of-the-art. Zero-shot vs few-shot prompting
- Min et al. 2022: random labels in the demos barely hurt classification accuracy; format and label space carry much of the effect. Zero-shot vs few-shot prompting
- Many-shot ICL (Agarwal et al. 2024): hundreds to thousands of examples in long context gave significant gains across many tasks. Zero-shot vs few-shot prompting
- DeepSeek-R1 paper: few-shot consistently degraded the reasoning model, so they recommend zero-shot. Zero-shot vs few-shot prompting
- Zero-shot CoT (Kojima 2022): InstructGPT went 17.7% → 78.7% on MultiArith and 10.4% → 40.7% on GSM8K. Chain-of-thought (CoT)
- Few-shot CoT (Wei 2022): PaLM 540B on GSM8K 17.9% → 56.9%; gains appeared only at ~100B+ parameters. Chain-of-thought (CoT)
- Sprague et al. 2024 meta-analysis: CoT's benefit concentrates on math and symbolic reasoning, with much smaller gains elsewhere. Chain-of-thought (CoT)
- Anthropic 2025: reasoning models mentioned a hint they had used only ~25% (Claude 3.7 Sonnet) and ~39% (DeepSeek-R1) of the time. Chain-of-thought (CoT)
- Reasoning and thinking tokens bill as output tokens, even when hidden or summarized. On Claude 4.6+, depth is set by adaptive thinking plus
effort;budget_tokensis rejected from 4.7 on (late 2026). Chain-of-thought (CoT) - OpenAI eval: gpt-4o-2024-08-06 with Structured Outputs scored 100% on complex schema following; gpt-4-0613 scored under 40%. Structured outputs & JSON mode
- Tam et al. 2024: stricter format constraints generally meant larger drops on reasoning tasks. Structured outputs & JSON mode
- 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. Structured outputs & JSON mode
- Anthropic reports that putting the question after long documents improves response quality by up to ~30% on complex multi-document inputs. Prompt techniques that matter
- Anthropic recommends 3–5 diverse, relevant examples for few-shot prompting. Prompt techniques that matter
- 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. Prompt techniques that matter
- Anthropic: a sub-agent may explore with tens of thousands of tokens but returns a condensed summary of ~1,000–2,000 tokens. Context engineering
- Anthropic's multi-agent researcher: ~15× chat tokens; token usage alone explained ~80% of performance variance on BrowseComp. Context engineering
- Anthropic reported that clearing stale tool results cut token use by 84% in a 100-turn web-search eval. Context engineering
- 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. Prompt caching
- Break-even with a 1.25× write and 0.1× read is the first reuse: two calls cost ~1.35× instead of 2×. Prompt caching
- 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. Prompt caching
- Anthropic's 2024 launch benchmark: a 100k-token cached prompt cut time to first token from 11.5 s to 2.4 s and cost by 90%. Prompt caching
- Minimum cacheable prefix depends on the model: 512–4,096 tokens on Claude, 1,024 on OpenAI, 2,048–4,096 for Gemini implicit caching. Shorter prompts never cache. Prompt caching
- 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. Long context vs RAG
- 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. Long context vs RAG
- RULER (2024): only about half of models claiming 32k+ windows held satisfactory performance at 32k. Long context vs RAG
- Worked example at $3/M input, 150k-token corpus: ~$0.45/query stuffed, ~$0.05 cached, ~$0.015 with 5k-token RAG. Long context vs RAG
- Liu et al.: ~20-point accuracy drop when the answer moves from the first to the middle position (GPT-3.5-Turbo, 20 documents). Lost in the middle & context rot
- RULER: of models claiming 32K+ context, only about half held up at 32K. Lost in the middle & context rot
- 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%. Lost in the middle & context rot
- Anthropic: putting the query after long documents improved response quality by up to 30% in its tests. Lost in the middle & context rot
- Rollout ladder: ~1–5% → 25–50% → 100%, holding at each step long enough to read online metrics. Prompts as code: versioning
- Start the CI golden set at ~50–200 cases per prompt; it must finish in minutes or people skip it. Prompts as code: versioning
- Registry fetches: client-side cache (TTL ~60 s, Langfuse's default) plus a bundled fallback, so an outage never blocks requests. Prompts as code: versioning
- Pinned snapshots still retire: in Oct 2026 OpenAI gave 3 months' notice that gpt-4o and gpt-4.1 snapshots shut down on Jan 14, 2027. Budget a re-eval per migration. Prompts as code: versioning
- Wang et al.: +17.9 points on GSM8K for PaLM 540B (40 sampled CoT paths vs greedy CoT). Self-consistency & best-of-N
- OpenAI o1 on AIME 2024: 74% with one sample, 83% with consensus over 64, 93% reranking 1,000 samples with a learned scorer. Self-consistency & best-of-N
- Cobbe et al.: a trained verifier on GSM8K gave roughly the boost of a 30× larger model. Self-consistency & best-of-N
- In production, N ≈ 3–10 is the usual range; benchmarks report 32–64+, with diminishing returns. Self-consistency & best-of-N
- OPRO: optimized prompts beat human-written ones by up to 8% on GSM8K and up to 50% on Big-Bench Hard tasks. Automatic prompt optimization (DSPy)
- 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". Automatic prompt optimization (DSPy)
- MIPRO: beat baseline optimizers on 5 of 7 multi-stage programs with Llama-3-8B, by up to 13% accuracy. Automatic prompt optimization (DSPy)
- TextGrad: lifted GPT-4o zero-shot accuracy on Google-Proof QA from 51% to 55%. Automatic prompt optimization (DSPy)
RAG & Retrieval
- Typical online shape: retrieve ~50 → rerank → 3–8 chunks of ~300–800 tokens in the prompt. RAG (Retrieval-Augmented Generation)
- Indexing is cheap: 75M tokens with text-embedding-3-small ($0.02 per 1M, list price as of 2026) ≈ $1.50. RAG (Retrieval-Augmented Generation)
- Retrieval + reranking usually add ~100–400 ms before the first token; generation dominates total latency. RAG (Retrieval-Augmented Generation)
- The original RAG paper retrieved from ~21M Wikipedia passages of 100 words. RAG (Retrieval-Augmented Generation)
- Managed OCR lists at ~$1.50 per 1,000 pages; layout or table extraction ~$10–15 per 1,000 (Azure, AWS list prices, 2026). Document ingestion & parsing
- Under ~100–200 extracted characters per page usually means a scan that needs OCR. Document ingestion & parsing
- Read 20–50 parsed documents by eye before tuning anything downstream. Document ingestion & parsing
- Common starting point: 300–800 tokens per chunk with 10–20% overlap. Chunking strategies
- Parent-child: children ~100–400 tokens, parents ~1,000–2,000 tokens or a whole section. Chunking strategies
- Many open embedding models cap input at 512 tokens (some at 256); longer text is silently truncated. Chunking strategies
- Anthropic's contextual retrieval prepends ~50–100 tokens of generated context to each chunk. Chunking strategies
- 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. Choosing an embedding model
- float32 storage = dims × 4 bytes: 1,024 dims ≈ 4 KB per vector, ~4 GB per 1M chunks. Choosing an embedding model
- OpenAI reports text-embedding-3-large cut to 256 dims still beats ada-002 at 1,536 dims on MTEB. Choosing an embedding model
- BGE-M3: 1,024 dims, up to 8,192 input tokens, 100+ languages, dense + sparse + multi-vector outputs. Choosing an embedding model
- Quantization: int8 is 4× smaller than float32, binary is 32× smaller. Choosing an embedding model
- 1M × 1536 dims × 4 B ≈ 6 GB of raw float32; int8 ≈ 1.5 GB; binary ≈ 0.2 GB. Vector databases
- pgvector indexes up to 2,000 dims for
vectorand 4,000 forhalfvec. Vector databases - pgvector HNSW defaults: m = 16, ef_construction = 64, hnsw.ef_search = 40. Vector databases
- HNSW links cost ~2·M × 4 B per vector (~130 B at M = 16): small next to a 6 KB vector. Vector databases
- Exact kNN over 10M × 768 float32 reads ~31 GB per query. ANN indexes: HNSW, IVF, PQ
- Common HNSW starting points: M = 16, efConstruction = 64–200, efSearch = 40–100 (and always ≥ k). ANN indexes: HNSW, IVF, PQ
- PQ at 1 byte per 16 dims: a 1536-dim float32 vector goes from 6 KB to 96 bytes (64×). ANN indexes: HNSW, IVF, PQ
- pgvector IVFFlat guidance: lists = rows/1000 up to 1M rows, √rows above; probes ≈ √lists. ANN indexes: HNSW, IVF, PQ
- DiskANN paper: a billion-point index on one workstation with 64 GB of RAM plus an SSD. ANN indexes: HNSW, IVF, PQ
- Lucene, Elasticsearch and OpenSearch defaults: k1 = 1.2, b = 0.75. Lexical search & BM25
- BM25 has been Lucene's default similarity since Lucene 6.0 (2016). Lexical search & BM25
- 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. Lexical search & BM25
- BEIR (18 datasets, 2021): out of domain, BM25 was a strong zero-shot baseline that many dense retrievers of the time failed to beat. Lexical search & BM25
- RRF: score = Σ 1/(k + rank), with k = 60 from Cormack et al. (2009). Hybrid search & RRF
- 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. Hybrid search & RRF
- Typical shape: top ~50 per retriever → fuse → rerank → keep 3–8. Hybrid search & RRF
- Anthropic: contextual embeddings + contextual BM25 cut top-20 retrieval failures by 49%, and by 67% with reranking. Hybrid search & RRF
- Typical shape: retrieve 50–100 → rerank → keep 3–8. Reranking (cross-encoders)
- Anthropic measured contextual retrieval + reranking cutting top-20 retrieval failures by 67%. Reranking (cross-encoders)
- Latency: +1 small-model call, ~0.2–1 s; produce rewrite, variants and HyDE passage in a single call. Query transformation (rewrite, HyDE)
- Multi-query: 3–5 variants → retrieval fan-out ×3–5 → fuse with RRF, score = Σ 1/(60 + rank). Query transformation (rewrite, HyDE)
- HyDE (Gao et al., 2022) is zero-shot: it beat the unsupervised Contriever retriever without any relevance labels. Query transformation (rewrite, HyDE)
- Top-20 retrieval failure rate in Anthropic's tests: 5.7% baseline → 3.7% with contextual embeddings (−35%). Contextual retrieval
- Adding contextual BM25: 2.9% (−49%); adding reranking on top: 1.9% (−67%). Contextual retrieval
- Generated context: ~50–100 tokens per chunk. Contextual retrieval
- ~$1.02 per million document tokens, one-time, with prompt caching (Claude 3 Haiku pricing, 2024); scale by your model's price. Contextual retrieval
- Under ~200K tokens (~500 pages) of knowledge, skip retrieval and send it all with caching. Contextual retrieval
- Post-filter math: a user who can read a fraction p of the corpus keeps ~p·k of k hits; 1% of 100 ≈ 1. Metadata filters & permission-aware retrieval
- Revocation delay = your ACL sync interval: a nightly batch can keep serving revoked access for up to ~24 h. Metadata filters & permission-aware retrieval
- pgvector 0.8+ adds iterative index scans so filtered HNSW queries keep returning enough rows. Metadata filters & permission-aware retrieval
- Liu et al. (2023), auditing 4 generative search engines: only ~51.5% of generated sentences were fully supported by their citations. Citations & grounding
- Same study: only ~74.5% of citations actually supported the sentence they were attached to. Citations & grounding
- Citation precision = citations that support their claim ÷ all citations; citation recall = fully supported claims ÷ all claims. Citations & grounding
- Anthropic reported its built-in Citations outperformed most custom implementations, raising recall accuracy by up to 15% (internal evals, Jan 2025). Citations & grounding
- Indexing cost ≈ one extraction call per chunk (plus optional "gleaning" retries) + one report per community. GraphRAG & knowledge graphs
- The GraphRAG paper evaluated on ~1–2M-token corpora (podcast transcripts, news articles). GraphRAG & knowledge graphs
- In the paper, 600-token chunks extracted ~2× the entity references of 2,400-token chunks. GraphRAG & knowledge graphs
- LazyGraphRAG: indexing cost on par with vector RAG, ~0.1% of full GraphRAG (Microsoft Research, 2024). GraphRAG & knowledge graphs
- N agent steps cost more than N× the input tokens of one-shot RAG: each call re-sends the growing transcript. Agentic RAG
- Self-RAG uses 4 reflection-token types: Retrieve, IsRel, IsSup, IsUse. Agentic RAG
- CRAG's retrieval evaluator is a fine-tuned T5-large (~0.77B params), not the generator LLM: grading can be cheap. Agentic RAG
- Rule of thumb: ~1–3 s for one-shot RAG vs ~10 s+ once the agent takes 3–5 steps. Agentic RAG
- ColBERT: 128-dim vector per token; queries padded or truncated to 32 tokens. Late interaction (ColBERT)
- Uncompressed: 300 tokens × 128 dims × 2 bytes (fp16) ≈ 77 KB per chunk vs ~4 KB for one 1,024-dim fp32 vector. Late interaction (ColBERT)
- ColBERTv2 residual compression (1–2 bits per dimension): 6–10× smaller index. Late interaction (ColBERT)
- PLAID: up to ~7× lower latency on GPU and ~45× on CPU vs vanilla ColBERTv2. Late interaction (ColBERT)
- ColPali: ~1,000 patch vectors of 128 dims per page image. Late interaction (ColBERT)
- GDPR: answer an erasure request without undue delay, normally within one month (Art. 12(3)). Index freshness & lifecycle
- 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. Index freshness & lifecycle
- Embedding inversion (vec2text) recovered 92% of 32-token inputs exactly from their embeddings. Index freshness & lifecycle
- Example SLA: p95 edit-to-searchable < 15 min; deletions < 1 h; alert on the measured lag. Index freshness & lifecycle
- MRR per question: first relevant doc at rank 1 → 1.0, rank 2 → 0.5, rank 5 → 0.2, not found → 0. Evaluating RAG
- Hit rate@50 of 0.80 means ~20% of questions never see a relevant doc: no generator can fix those. Evaluating RAG
- RAGAS core metrics: faithfulness, answer relevancy, context precision, context recall. Evaluating RAG
- TruLens RAG triad: context relevance, groundedness, answer relevance. Evaluating RAG
Agents & Tool Use
- Anthropic (2025): agents use ~4× the tokens of a chat interaction; multi-agent systems ~15×. Agents vs workflows
- Compounding: at 95% per-step reliability a 10-step run succeeds ~60% of the time (0.95¹⁰ ≈ 0.60); at 99%, ~90%. Agents vs workflows
- 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. Agents vs workflows
- τ-bench (2024): gpt-4o function-calling agents solved <50% of tasks, and pass^8 (all 8 retries succeed) was <25% in retail. Tool / function calling
- 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). Tool / function calling
- Rule of thumb: a tool definition costs ~50–300 tokens, so 30 tools add several thousand tokens to every call. Tool / function calling
- Latency: N sequential tool steps ≈ N model calls; independent calls returned in one parallel turn cost one. Tool / function calling
- ReAct paper: +34 and +10 points absolute success over imitation and RL baselines on ALFWorld and WebShop, prompted with only 1–2 examples. ReAct: the agent loop
- On HotpotQA, ReAct alone slightly trailed chain-of-thought; combining it with self-consistent CoT scored best. On FEVER, ReAct beat CoT. ReAct: the agent loop
- 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. ReAct: the agent loop
- Rule of thumb: set the step cap at ~2–3× the steps a typical successful run needs, measured from traces. ReAct: the agent loop
- Claude Code caps tool responses at 25,000 tokens by default (Anthropic, 2025). Designing tools for agents (ACI)
- OpenAI guidance: aim for fewer than ~20 functions available at once, a soft limit for accuracy. Designing tools for agents (ACI)
- 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. Designing tools for agents (ACI)
- Rule of thumb: keep typical tool outputs in the hundreds of tokens, with a default page
limitof ~10–50 items. Designing tools for agents (ACI) - Reliability multiplies: five steps at 95% each ≈ 77% end-to-end (0.95⁵). Gates exist to break this math. Pattern: prompt chaining
- Latency is additive: end-to-end ≈ sum of step latencies, plus any retries the gates trigger. Pattern: prompt chaining
- A code gate costs microseconds and $0; an LLM-judge gate adds a full call (~0.5–3 s). Prefer code gates where possible. Pattern: prompt chaining
- 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). Pattern: routing
- RouteLLM (2024): learned routers cut cost by over 2× on some benchmarks without losing response quality. Pattern: routing
- FrugalGPT (2023): an LLM cascade matched GPT-4's performance with up to 98% lower cost on its benchmarks. Pattern: routing
- Rule of thumb for router overhead: a small-LLM call adds a few hundred ms; a local embedding or fine-tuned classifier, ~1–20 ms. Pattern: routing
- Rule of thumb: wall-clock ≈ max(branch latencies); cost ≈ sum of all branches. Pattern: parallelization
- 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. Pattern: parallelization
- Independence math: 3 voters each catching 70% of bugs → any-of ~97%, majority ~78%. Only if their errors were independent, which they rarely are. Pattern: parallelization
- Rule of thumb: 3–5 voters is a common starting point; add more only if the eval curve still rises. Pattern: parallelization
- Anthropic (2025): an Opus 4 lead with Sonnet 4 subagents beat single-agent Opus 4 by 90.2% on its internal research eval. Pattern: orchestrator–workers
- Same post: agents use ~4× the tokens of chat; multi-agent systems ~15×. Pattern: orchestrator–workers
- In Anthropic's BrowseComp analysis, token usage alone explained ~80% of the performance variance. Pattern: orchestrator–workers
- Spinning up 3–5 subagents in parallel (plus parallel tool calls) cut research time by up to 90% on complex queries. Pattern: orchestrator–workers
- Self-Refine (2023): iterative self-feedback improved task performance by ~20% absolute on average across 7 tasks. Pattern: evaluator–optimizer
- Reflexion (2023): feedback from test runs lifted HumanEval pass@1 to 91%, versus 80% for GPT-4 alone. Pattern: evaluator–optimizer
- Huang et al. (2023): without external feedback, self-correction did not improve reasoning benchmarks and sometimes lowered accuracy. Pattern: evaluator–optimizer
- Rule of thumb: cap at 2–4 rounds; most of the gain usually lands in the first one or two revisions. Pattern: evaluator–optimizer
- ReWOO (Xu et al., 2023): ~5× token efficiency and +4% accuracy on HotpotQA versus interleaved reasoning. Planning (plan-and-execute)
- 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. Planning (plan-and-execute)
- Rule of thumb: 3–10 steps per plan, each with a "done when" check; cap replans at 2–3, then escalate. Planning (plan-and-execute)
- 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. Agent memory
- Rule of thumb: inject ~5–10 memories (a few hundred to ~2k tokens) per turn, never the full transcript. Agent memory
- GDPR Art. 17 (right to erasure): deletion must reach memory rows, embeddings and derived summaries, not just the chat log. Agent memory
- Launched Nov 2024; OpenAI, Google and Microsoft announced support between Mar and May 2025. Model Context Protocol (MCP)
- 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. Model Context Protocol (MCP)
- Integration math: 5 apps × 20 systems = 100 bespoke connectors; with MCP, 5 + 20 = 25 implementations. Model Context Protocol (MCP)
- Anthropic measured 58 tools from 5 servers (GitHub, Slack, Sentry, Grafana, Splunk) at ~55k tokens of definitions before the conversation starts. Model Context Protocol (MCP)
- Anthropic: calling MCP tools from code execution instead of direct tool calls cut one workflow from ~150k to ~2k tokens (~98.7%). Model Context Protocol (MCP)
- 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. Agent-to-agent protocols (A2A)
- 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.jsonpath. Agent-to-agent protocols (A2A) - v1.0 (12 Mar 2026): PascalCase operations (
SendMessage,GetTask, newListTasks),TASK_STATE_*enums, Parts withoutkind,supportedInterfacesreplacing the card'surl, mandatoryA2A-Versionheader. Agent-to-agent protocols (A2A) - Rule of thumb: each agent hop is a full LLM loop (seconds to minutes), so keep delegation chains to 1–2 hops. Agent-to-agent protocols (A2A)
- Anthropic research system: a single agent uses ~4× the tokens of a chat; multi-agent ~15×. Multi-agent systems
- Anthropic: an Opus 4 lead with Sonnet 4 subagents beat single-agent Opus 4 by 90.2% on its internal research eval. Multi-agent systems
- Anthropic: token usage alone explained ~80% of the performance variance on BrowseComp. Multi-agent systems
- MAST (Cemri et al., 2025): 14 failure modes in 3 groups — specification, inter-agent misalignment, verification. Multi-agent systems
- 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). Computer use & browser agents
- OpenAI CUA (Jan 2025): 58.1% on WebArena and 87% on WebVoyager — curated web tasks are easier than full desktops. Computer use & browser agents
- 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). Computer use & browser agents
- Claude for Chrome pilot (Aug 2025): prompt-injection attack success fell from 23.6% to 11.2% with mitigations — lower, not zero. Computer use & browser agents
- AWS Step Functions: Standard workflows run up to 1 year; Express workflows up to 5 minutes. Durable execution for agents
- Step Functions caps each state's input/output at 256 KB: keep transcripts in S3 and pass pointers. Durable execution for agents
- Temporal: event history caps at 51,200 events or 50 MB per execution; use Continue-As-New for long agents. Durable execution for agents
- Stripe may drop idempotency keys after 24 hours: a retry window, not a forever guarantee. Durable execution for agents
- Rule of thumb: tier by blast radius — read-only auto, writes approve, money/deletes/permissions explicit confirm. Human-in-the-loop & approvals
- Alert-fatigue precedent: clinicians override 49–96% of drug-safety alerts (van der Sijs et al., 2006). Human-in-the-loop & approvals
- Anthropic: sandboxing cut Claude Code permission prompts by 84% internally — fewer prompts, more attention per prompt. Human-in-the-loop & approvals
- Rule of thumb: if >95% of an action's approvals pass unchanged, auto-approve it with sampling. Human-in-the-loop & approvals
- Compounding: 0.95^20 ≈ 36%, 0.99^20 ≈ 82%, 0.90^10 ≈ 35%. Agent reliability: budgets & loops
- τ-bench (2024): GPT-4o solved <50% of tasks, and pass^8 in retail fell below 25%. Agent reliability: budgets & loops
- Rule of thumb: cap steps at ~2–3× the median successful run; stop on the 3rd identical tool call. Agent reliability: budgets & loops
Evaluation
- Rule of thumb: start with ~20–50 cases drawn from real failures; hundreds come later, from production traces. Eval-driven development
- Noise floor: at n=100 and an 80% pass rate, the 95% CI is ~±8 points; at n=1,000, ~±2.5. Eval-driven development
- Hamel Husain's three levels: assertions on every commit → human + model eval on a cadence → A/B tests for big changes. Eval-driven development
- Rule of thumb: review ~100 traces per round, and keep going until new traces stop revealing new failure modes. Error analysis: look at your data
- Typical shape (rule of thumb): a handful of modes, often 3–6, covers most failures: Pareto, not uniform. Error analysis: look at your data
- Effort (rule of thumb): with a good trace viewer, 100 traces is a few hours of reading, not days. Error analysis: look at your data
- Rule of thumb: start with ~50–200 cases; grow toward several hundred to ~1,000 as slices multiply. Golden datasets & test sets
- At an 80% pass rate the 95% CI is ~±8 points with 100 cases and ~±4 with 400. Golden datasets & test sets
- A 25-case slice at 80% carries a ~±16-point 95% CI: per-slice reads need more cases or bigger effects. Golden datasets & test sets
- Rule of thumb: ~10–20% no-answer or out-of-scope cases, so abstention is actually tested. Golden datasets & test sets
- HumanEval: 164 hand-written Python problems, graded by unit tests and reported as pass@k (Chen et al., 2021). Code-based graders & assertions
- Unbiased pass@k from n samples with c correct: 1 − C(n−c, k) / C(n, k), averaged over problems. Code-based graders & assertions
- SWE-bench: 2,294 real GitHub issues from 12 Python repos, graded by running each repo's own tests. Code-based graders & assertions
- Cost gap: a code check is ~milliseconds and $0; a judge call is ~seconds plus tokens, on every case, every run. Code-based graders & assertions
- 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. LLM-as-a-judge
- Same paper: with the answer order swapped, even GPT-4 kept its verdict only ~65% of the time. LLM-as-a-judge
- Rule of thumb: calibrate on ~100–200 human-labeled examples; aim for judge TPR and TNR of ~0.9 or better. LLM-as-a-judge
- Landis & Koch (1977) kappa bands: 0.41–0.60 moderate, 0.61–0.80 substantial, 0.81–1.00 almost perfect. Human evaluation & annotation
- Why kappa: if both raters mark ~90% PASS, chance agreement is 82%, so 90% raw agreement is only κ ≈ 0.44. Human evaluation & annotation
- Rule of thumb: ~50 double-labeled items to estimate agreement; ~100–200 labels to calibrate a judge. Human evaluation & annotation
- F1 = 2PR / (P + R): precision 0.9 with recall 0.5 gives F1 ≈ 0.64, not the 0.7 average. Precision, recall, F1, ROC-AUC
- Base rate: at 1% prevalence, 99% recall with a 1% false-positive rate still gives only ~50% precision. Precision, recall, F1, ROC-AUC
- Random baselines: ROC-AUC = 0.5 at any class balance; PR-AUC = the positive rate (e.g. 0.01). Precision, recall, F1, ROC-AUC
- At 1% positives, an always-negative model scores 99% accuracy and 0 recall. Precision, recall, F1, ROC-AUC
- RAGAS faithfulness = claims supported by the retrieved context ÷ total claims in the answer (0–1). Measuring hallucination & groundedness
- FActScore (Min et al., 2023): only ~58% of the atomic facts in ChatGPT-generated biographies were supported. Measuring hallucination & groundedness
- 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. Measuring hallucination & groundedness
- τ-bench (Yao et al., 2024): gpt-4o function-calling agents solved <50% of tasks, and pass^8 was <25% in the retail domain. Evaluating agents
- Independent trials at 90% per-trial success: pass^8 = 0.9^8 ≈ 43%, while pass@8 ≈ 100%. Evaluating agents
- 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. Evaluating agents
- Rule of thumb: start with 20–50 tasks from real failures, 3–10 trials each. Evaluating agents
- 95% CI half-width ≈ 1.96·√(p(1−p)/n): at 50%, n=100 → ±~10 pts; n=400 → ±~5; n=1,000 → ±~3. Non-determinism: pass@k & variance
- pass^k ≈ p^k for independent trials: 90% per run → ~73% for 3 in a row, ~59% for 5. Non-determinism: pass@k & variance
- Codex (2021): 28.8% of HumanEval with 1 sample, 70.2% with 100 samples per problem. Non-determinism: pass@k & variance
- τ-bench (2024): GPT-4o solved <50% of tasks, and pass^8 fell below 25% in the retail domain. Non-determinism: pass@k & variance
- Rule of thumb: canary at ~1–5% of users, then staged ramps (e.g., 25% → 50% → 100%) gated on guardrails. Offline vs online evaluation
- Judge precision depends on volume, not percentage: ~400 judged traces give ±~5 pts at 95%, ~100 give ±~10. Offline vs online evaluation
- GitHub Copilot study (Ziegler et al., 2022): the acceptance rate of shown suggestions predicted perceived productivity better than other usage metrics. Offline vs online evaluation
- 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. A/B testing LLM features
- Peeking: 10 interim looks at p < 0.05 push the real false-positive rate to ~19% (Armitage et al.). A/B testing LLM features
- 20 metrics at α=0.05 → ~64% chance at least one shows a false "win" (1 − 0.95²⁰). A/B testing LLM features
- CUPED at Microsoft (Deng et al., 2013): ~50% variance reduction on some Bing metrics, the same power with ~half the traffic. A/B testing LLM features
- Rule of thumb: run at least 1–2 full weeks to cover weekly cycles and let novelty fade. A/B testing LLM features
- Sizes: HumanEval 164 problems; GPQA Diamond 198; SWE-bench Verified 500; MMLU ~16k questions in 57 subjects. Public benchmarks & contamination
- 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). Public benchmarks & contamination
- GPQA: experts with or pursuing PhDs score ~65% (~74% excluding clear mistakes); skilled non-experts with web access ~34%. Public benchmarks & contamination
- MMLU-Redux (2024): ~6.5% of MMLU questions contain errors, so gaps near 90% partly measure label noise. Public benchmarks & contamination
- GPT-3 paper (2020): contamination measured as 13-gram overlap between benchmark items and training data. Public benchmarks & contamination
- Rule of thumb: PR subset of ~50–200 cases in under ~10 minutes; full suite nightly and before each release. Evals in CI/CD & release gates
- 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. Evals in CI/CD & release gates
- Dated snapshots (e.g., gpt-4o-2024-08-06) stay fixed; aliases like gpt-4o get repointed to newer snapshots over time. Evals in CI/CD & release gates
Fine-tuning & Adaptation
- LIMA: ~1,000 curated examples taught LLaMA-65B the assistant format (Zhou et al., 2023). Prompt → RAG → fine-tune: the decision
- InstructGPT: labelers preferred a 1.3B tuned model over 175B GPT-3. Adaptation can beat size. Prompt → RAG → fine-tune: the decision
- 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). Prompt → RAG → fine-tune: the decision
- OpenAI's SFT guide: at least 10 examples, gains usually from 50–100 (its platform closed to new users in 2026). Prompt → RAG → fine-tune: the decision
- LIMA: ~1,000 curated examples aligned LLaMA-65B competitively (Zhou et al., 2023). Supervised fine-tuning (SFT)
- InstructGPT's SFT set was only ~13k prompts with labeler-written answers. Supervised fine-tuning (SFT)
- OpenAI's SFT guide: minimum 10 examples; gains typically from 50–100 (platform closed to new users, 2026). Supervised fine-tuning (SFT)
- Rule of thumb: 1–3 epochs; LR ~1e-5–2e-5 full, ~1e-4–2e-4 LoRA. Supervised fine-tuning (SFT)
- Qi et al. (2023): 10 adversarial examples (<$0.20) undid GPT-3.5 Turbo's safety tuning. Supervised fine-tuning (SFT)
- LoRA on GPT-3 175B: ~10,000× fewer trainable parameters, ~3× less GPU memory, checkpoint 350 GB → ~35 MB. LoRA & QLoRA
- QLoRA: 65B model fine-tuned on one 48 GB GPU, matching 16-bit fine-tuning (Dettmers et al., 2023). LoRA & QLoRA
- 8B model, r=16 on all linear layers: ~42M trainable parameters, about 0.5%. LoRA & QLoRA
- Rule of thumb: r = 8–64, alpha ≈ r to 2r, LR ~1e-4–2e-4. LoRA & QLoRA
- S-LoRA: thousands of concurrent adapters served over one shared base model. LoRA & QLoRA
- InstructGPT: labelers preferred the 1.3B RLHF model over 175B GPT-3, with 100× fewer parameters. RLHF: reinforcement learning from human feedback
- InstructGPT data: ~13k SFT prompts, ~33k reward-model prompts, ~31k PPO prompts, ~40 contract labelers. RLHF: reinforcement learning from human feedback
- InstructGPT ranked 4–9 responses per prompt, giving up to 36 pairs per ranking. RLHF: reinforcement learning from human feedback
- Llama 2-Chat: over 1M human binary comparisons collected by Meta. RLHF: reinforcement learning from human feedback
- PPO-based RLHF holds 4 models: policy, reference, reward and value (critic). DPO needs 2. RLHF: reinforcement learning from human feedback
- β ≈ 0.1 is the usual default (TRL's); sweeps commonly span ~0.01–0.5. DPO & preference optimization
- Memory: PPO-based RLHF holds 4 models (policy, reference, reward, value); DPO holds 2; ORPO and SimPO hold 1. DPO & preference optimization
- Zephyr-7B: SFT + DPO on ~60k GPT-4-scored UltraFeedback pairs beat Llama-2-70B-chat on MT-Bench. DPO & preference optimization
- Llama 3 post-training chose DPO over PPO, citing less compute at scale and better instruction following. DPO & preference optimization
- Rule of thumb: learning rate ~5e-7 to 1e-6 for full fine-tuning, far below SFT's ~1e-5. DPO & preference optimization
- DeepSeek-R1-Zero: AIME 2024 pass@1 rose from 15.6% to 71.0% with pure RL (86.7% with majority voting). RL with verifiable rewards (GRPO)
- GRPO group size: commonly 8–64 samples per prompt; TRL's default is 8. RL with verifiable rewards (GRPO)
- Rule of thumb: keep prompts the model solves ~10–90% of the time; all-pass or all-fail groups give zero advantage. RL with verifiable rewards (GRPO)
- GRPO was introduced in DeepSeekMath (Feb 2024); the term RLVR was coined in AI2's Tülu 3 (Nov 2024). RL with verifiable rewards (GRPO)
- DistilBERT: ~40% smaller (66M vs 110M parameters), ~60% faster, keeps ~97% of BERT's GLUE performance. Knowledge distillation
- 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. Knowledge distillation
- Same paper: distilling R1 into Qwen-32B beat running large-scale RL on it directly (72.6% vs ~47% on AIME). Knowledge distillation
- Hinton's soft targets use a temperature T > 1 and scale the soft loss by T² to keep gradients comparable. Knowledge distillation
- Self-Instruct: 175 human seed tasks grew into ~52k instructions; Stanford's Alpaca reproduced it for under $500 of API calls. Synthetic data
- Nemotron-4 340B: over 98% of the data used in its alignment process was synthetic. Synthetic data
- 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. Synthetic data
- Persona Hub: 1B personas (~13% of the world's population) to diversify generation. Synthetic data
- LIMA: 1,000 curated SFT examples; its answers were equal to or preferred over GPT-4's in 43% of comparisons. Training data quality & curation
- Lee et al.: C4 held one 61-word sentence 60,000+ times; deduplication cut verbatim memorized output ~10×. Training data quality & curation
- FineWeb-Edu: ~1.3T of FineWeb's ~15T tokens, kept by a classifier trained on ~450k Llama-3-70B ratings. Training data quality & curation
- DCLM-Baseline: a 7B model reached 64% 5-shot MMLU on 2.6T tokens, driven mainly by model-based filtering. Training data quality & curation
- Llama 3's final pretraining mix: ~50% general knowledge, 25% math and reasoning, 17% code, 8% multilingual. Training data quality & curation
- Qi et al. 2023: 10 adversarial examples and under $0.20 of API fine-tuning jailbroke GPT-3.5 Turbo's safety guardrails. Catastrophic forgetting
- Biderman et al. 2024: full fine-tuning learns weight changes of 10–100× higher rank than typical LoRA configs. Catastrophic forgetting
- Rule of thumb: 1–3 epochs for SFT; more epochs, more forgetting. Catastrophic forgetting
- Rule of thumb: replay ~5–20% general data in the training mix. Catastrophic forgetting
- Typical learning rates: ~1e-5–2e-5 for full fine-tuning, ~1e-4–2e-4 for LoRA. Catastrophic forgetting
- Training compute ≈ 6 × params × tokens FLOPs: 8B params on 10B tokens ≈ 4.8e20, ~340 H100-hours at 40% MFU. Continued pretraining
- Code Llama: Llama 2 continued on 500B code tokens (+100B Python tokens for the Python variant). Continued pretraining
- Meditron: Llama 2 continued on ~48B tokens of medical text. Continued pretraining
- BloombergGPT: 50B params trained from scratch on a corpus of 363B financial + 345B general tokens. Continued pretraining
- Rule of thumb: replay ~5–25% general data, more for bigger shifts such as a new language. Continued pretraining
- MNRL: a batch of B pairs gives each query B−1 free in-batch negatives; default scale 20 (temperature 0.05). Fine-tuning embeddings & rerankers
- Rule of thumb: ~1k–10k good pairs move a base-size (~110M) model; training takes minutes to an hour on one GPU. Fine-tuning embeddings & rerankers
- Rule of thumb: sample hard negatives from ranks ~10–50, not the top few, where false negatives live. Fine-tuning embeddings & rerankers
- Re-index cost: 10M chunks × ~500 tokens = 5B tokens to re-embed after every model change. Fine-tuning embeddings & rerankers
- Mixed-precision Adam ≈ 16 bytes/param before activations: 7B ≈ 112 GB, 70B ≈ 1.1 TB. Distributed training: DP, TP, PP, FSDP
- ZeRO-3/FSDP: per-GPU state ≈ 16 × params / N, at ~1.5× DDP's communication volume. Distributed training: DP, TP, PP, FSDP
- Pipeline bubble ≈ (p−1)/(m+p−1) of step time: 4 stages, 16 micro-batches → ~16% idle. Distributed training: DP, TP, PP, FSDP
- H100 NVLink ~900 GB/s per GPU vs ~100 GB/s for a 400 Gb/s InfiniBand link (both bidirectional, ~9×): TP stays inside the node. Distributed training: DP, TP, PP, FSDP
- Llama 3 405B: 4D parallelism (TP, CP, PP, FSDP) on up to 16K H100s at ~38–43% MFU. Distributed training: DP, TP, PP, FSDP
Inference, Serving & Cost
- E2E ≈ TTFT + TPOT × (output tokens − 1); per-user speed = 1/TPOT (20 ms → 50 tokens/s). Latency metrics: TTFT, TPOT, throughput
- People read ~200–300 words/min ≈ ~4–7 tokens/s; streaming at ~10+ tokens/s outpaces them. Latency metrics: TTFT, TPOT, throughput
- 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. Latency metrics: TTFT, TPOT, throughput
- Rule of thumb for chat: p95 TTFT under ~1 s and TPOT under ~50 ms (20+ tokens/s). Latency metrics: TTFT, TPOT, throughput
- Forward pass ≈ 2 FLOPs per parameter per token: an 8B model prefilling 2k tokens ≈ 32 TFLOPs. Prefill vs decode
- Batch-1 decode ≈ 1 FLOP per byte of FP16 weights; an H100 needs ~300 (989 TFLOPS ÷ 3.35 TB/s) to be compute-bound. Prefill vs decode
- Output lists at ~4–8× input (2025 list prices): GPT-4o $2.50 vs $10, Claude Sonnet $3 vs $15 per million tokens. Prefill vs decode
- DistServe: up to 7.4× more requests or 12.6× tighter SLOs than co-located serving, keeping >90% of requests within SLO. Prefill vs decode
- Weights: 70B ≈ 140 GB in FP16, ~70 GB in FP8, ~35 GB in INT4 (+ scales). GPU memory math
- KV per token in FP16: Llama-3-8B 128 KiB, Llama-3-70B 320 KiB. GPU memory math
- H100 SXM: 80 GB HBM3 at ~3.35 TB/s; H200: 141 GB at ~4.8 TB/s; A100 80 GB: ~2 TB/s. GPU memory math
- Batch-1 decode ceiling = bandwidth ÷ weight bytes: 7B FP16 on A100 ≈ 140 tokens/s. GPU memory math
- vLLM default gpu_memory_utilization = 0.9: 90% of each GPU for weights, activations and KV. GPU memory math
- Orca: 36.9× throughput over NVIDIA FasterTransformer at the same latency (GPT-3 175B). Continuous batching
- Anyscale benchmark: up to ~23× throughput vs naive static batching (with vLLM), while also lowering p50 latency. Continuous batching
- vLLM (PagedAttention + continuous batching): 2–4× throughput over FasterTransformer and Orca at the same latency. Continuous batching
- Static batch cost = longest sequence × batch size: a 50-token answer next to a 1,000-token one wastes ~95% of its slot. Continuous batching
- Pre-vLLM servers used only 20–38% of KV memory for real tokens; vLLM wastes under 4%. PagedAttention & vLLM
- 2–4× throughput vs FasterTransformer/Orca at equal latency (paper); up to 24× vs plain HF Transformers (vLLM launch blog). PagedAttention & vLLM
- Sharing cuts the memory of parallel sampling and beam search by up to 55% (vLLM blog). PagedAttention & vLLM
- Defaults: 16 tokens per block;
gpu_memory_utilization=0.9. PagedAttention & vLLM - A100: ~20 MB of on-chip SRAM at ~19 TB/s vs 40–80 GB of HBM at ~1.5–2 TB/s. FlashAttention
- FA-1: 3× faster GPT-2 training at 1k tokens; 10–20× attention memory saving at 2k–4k. FlashAttention
- FA-2: ~2× FA-1, reaching 50–73% of A100 peak FLOPs/s. FlashAttention
- FA-3 on H100: 1.5–2× FA-2, up to ~740 TFLOPs/s in FP16 (~75% utilization), ~1.2 PFLOPs/s in FP8. FlashAttention
- Bytes per parameter: BF16 2, FP8/INT8 1, INT4 0.5. A 70B model is ~140 / ~70 / ~35 GB, plus ~5–10% for scales. Quantization (INT8, INT4, FP8)
- 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. Quantization (INT8, INT4, FP8)
- GPTQ quantized 175B-parameter models to 3–4 bits in ~4 GPU hours. Quantization (INT8, INT4, FP8)
- QLoRA's double quantization saves ~0.37 bits per parameter (~3 GB on a 65B model). Quantization (INT8, INT4, FP8)
- Leviathan et al.: 2–3× on T5-XXL with identical outputs; Chen et al.: 2–2.5× on Chinchilla 70B. Speculative decoding
- Expected tokens per target pass = (1 − α^(k+1)) / (1 − α); acceptance α = 0.8, k = 4 → ~3.4. Speculative decoding
- Medusa-2: 2.3–3.6×; EAGLE: 2.7–3.5× on LLaMA2-Chat 70B (papers). Speculative decoding
- DeepSeek-V3's multi-token prediction: 85–90% acceptance of the second token, ~1.8× tokens/s. Speculative decoding
- Weights ≈ params × bytes: 70B in BF16 ≈ 140 GB → at least 2× 80 GB GPUs, usually 4 for KV-cache headroom. Self-hosted serving stack
- vLLM pre-allocates 90% of GPU memory by default (
--gpu-memory-utilization 0.9), mostly for KV cache. Self-hosted serving stack - SGLang paper (2023): up to 6.4× higher throughput than prior systems on structured, prefix-sharing workloads. Self-hosted serving stack
- H100 NVLink ~900 GB/s vs ~50 GB/s for a 400 Gb/s NIC: why tensor parallelism stays inside a node. Self-hosted serving stack
- Cold-start floor: 140 GB at ~1 GB/s is ~2.3 minutes for the bytes alone, before node provisioning and warm-up. Self-hosted serving stack
- A month is ~730 hours: a rented GPU bills all of them, busy or idle. API vs self-hosting
- Self-host cost per token = GPU $/hour ÷ tokens per hour actually served: halve utilization, double the unit cost. API vs self-hosting
- Batch APIs cut prices ~50% for results within 24 h (OpenAI, Anthropic, Gemini). API vs self-hosting
- Worked example (assumptions in the code): ~$0.62/M at 60% utilization vs $0.80/M via API → crossover ~60–90B tokens/month once ops is counted. API vs self-hosting
- ~4 characters ≈ 1 token ≈ 0.75 English words (OpenAI rule of thumb). Token economics & cost estimation
- 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. Token economics & cost estimation
- Cached input reads: ~0.1× base on Anthropic; 50–90% off on OpenAI depending on the model. Token economics & cost estimation
- Batch APIs: ~50% off for results within 24 h. Token economics & cost estimation
- History: if each turn adds k tokens, N turns send ~k·N²/2 input tokens in total. Token economics & cost estimation
- RouteLLM (LMSYS, 2024): over 2× cost reduction at similar quality; ~85% cheaper than GPT-4-only on MT Bench at 95% of its quality. Model routing & cascades
- FrugalGPT (2023): cascades matched GPT-4 quality at up to 98% lower cost on its benchmarks. Model routing & cascades
- Cascade cost = small + P(escalate) × large: a 20× cheaper model with 25% escalation costs ~30% of all-large. Model routing & cascades
- Price gap to exploit: GPT-4.1 $2 vs GPT-4.1-nano $0.10 per 1M input tokens (20×, 2025 list). Model routing & cascades
- Typical cosine threshold ~0.90–0.95 on normalized embeddings; tune it on labeled query pairs (rule of thumb). Semantic caching
- A hit = one embedding call + one vector lookup: tens of ms vs seconds for a generation. Semantic caching
- text-embedding-3-small: $0.02 per 1M tokens (OpenAI list price, unchanged as of Nov 2026), so lookups are close to free. Semantic caching
- Savings ≈ hit rate × LLM cost: a 20% hit rate saves ~20%, minus embedding and store costs. Semantic caching
- Provider limits are two-dimensional: requests/min and tokens/min (Anthropic splits input and output TPM). Your quotas must be too. LLM gateway
- Retry 429, 500/502/503, 529 (Anthropic overloaded) and timeouts with backoff + jitter; never retry 400/401/403. LLM gateway
- Rule of thumb: a gateway should add single-digit ms per call, negligible next to hundreds of ms of TTFT. LLM gateway
- LiteLLM exposes 100+ providers behind the OpenAI API format. LLM gateway
- 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. Streaming responses (SSE)
- Rule of thumb: hosted models decode ~50–100 output tokens/s per stream, so a 500-token answer is 5–10 s unstreamed. Streaming responses (SSE)
- Browsers allow ~6 HTTP/1.1 connections per origin; open SSE streams count against it, so serve them over HTTP/2. Streaming responses (SSE)
- AWS ALB's default idle timeout is 60 s: send heartbeat comments during long pauses such as reasoning. Streaming responses (SSE)
- OpenAI Batch and Anthropic Message Batches: ~50% off standard prices, results within 24 h, often much sooner. Batch inference
- Per batch: OpenAI up to 50,000 requests and 200 MB; Anthropic up to 100,000 requests or 256 MB. Batch inference
- Anthropic keeps batch results for 29 days, and its batch discount stacks with prompt caching. Batch inference
- Cost math: items × (input tokens × input price + output tokens × output price) × 0.5. Output tokens usually cost ~4–8× input. Batch inference
- OTel GenAI core attributes: gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens. Capturing message content is opt-in. LLM observability & tracing
- Rule of thumb for sampling: metrics on 100% of requests; full payloads on all errors and negative feedback plus ~1–10% of the rest. LLM observability & tracing
- Rule of thumb: ~4 characters per English token, so payload storage is ~4 bytes × tokens per span. LLM observability & tracing
- Four dashboards: cost (per team, feature, model), latency (TTFT and total at p50/p95/p99), errors (429, 5xx, timeouts, refusals), quality (feedback, online eval scores). LLM observability & tracing
Security, Safety & Governance
- Term coined Sept 2022 (Simon Willison); indirect injection formalized Feb 2023 (Greshake et al.). Prompt injection (direct & indirect)
- #1 in the OWASP Top 10 for LLM apps in every edition so far: 2023, 2025 and 2026 (LLM01). Prompt injection (direct & indirect)
- Rule of thumb: a 99%-accurate detector still lets 1 in 100 attempts through, and attackers retry. In security, 99% is a failing grade. Prompt injection (direct & indirect)
- AgentDojo (2024), a standard benchmark for defenses: 97 agent tasks, 629 injection test cases. Prompt injection (direct & indirect)
- 3 legs; removing any 1 closes this exfiltration path (not the others). The lethal trifecta
- 0 clicks: a rendered markdown image fetches its URL automatically, a classic exfiltration channel. The lethal trifecta
- Rule of Two (Meta, Oct 2025): at most 2 of the 3 properties per session; all 3 needs human supervision. The lethal trifecta
- EchoLeak (CVE-2025-32711, June 2025): zero-click data exfiltration from Microsoft 365 Copilot via one crafted email. The lethal trifecta
- Constitutional Classifiers (Anthropic, Feb 2025): automated jailbreak success 86% → 4.4%, with +0.38% refusals and 23.7% compute overhead. Jailbreaks
- Their 2024 bug bounty: 183 red-teamers, 3,000+ hours, no universal jailbreak; the Feb 2025 public demo (~3,700 hours) produced one. Jailbreaks
- Many-shot (Anthropic, 2024): success scales with shot count; one prompt-classification mitigation cut attack success from 61% to 2%. Jailbreaks
- Best-of-N (2024): with 10,000 randomly augmented tries, ~89% success on GPT-4o and ~78% on Claude 3.5 Sonnet. Retries are the attack. Jailbreaks
- Next-generation Constitutional Classifiers (Anthropic, Jan 2026): ~1% compute overhead, 0.05% refusal rate, 1,700+ red-team hours without a universal jailbreak. Jailbreaks
- 10 risks, LLM01–LLM10; current edition is 2026 (published Aug 2026); earlier editions 2025 (Nov 2024) and 2023. OWASP Top 10 for LLM apps
- Prompt Injection is #1 in all three editions; Sensitive Information Disclosure has been #2 since 2025. OWASP Top 10 for LLM apps
- 2026: 8 of 10 entries changed rank; Excessive Agency rose from #6 to #3, Improper Output Handling fell from #5 to #10. OWASP Top 10 for LLM apps
- 1 rename in 2026: System Prompt Leakage (LLM07:2025) became Hidden Context Exposure (LLM08:2026). OWASP Top 10 for LLM apps
- OWASP Top 10 for Agentic Applications: Dec 2025, ASI01–ASI10, with ASI01 Agent Goal Hijack. OWASP Top 10 for LLM apps
- 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. Guardrails: input, output, action
- Meta's Prompt Guard 2 injection/jailbreak classifier ships at 86M and 22M parameters: cheap enough to run on every request. Guardrails: input, output, action
- Rule of thumb: regex <1 ms, small classifier ~10–50 ms, LLM-based guard ~0.2–1 s or more if run in series. Guardrails: input, output, action
- OpenAI's moderation endpoint is free to use. Guardrails: input, output, action
- GDPR fines: up to €20M or 4% of global annual turnover, whichever is higher. PII & data privacy
- GDPR: answer an erasure or access request within 1 month; notify the authority of a breach within 72 h. PII & data privacy
- 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. PII & data privacy
- vec2text recovered 92% of 32-token inputs exactly from their embeddings: treat embeddings as personal data. PII & data privacy
- ChatGPT, March 2023: a
redis-pybug exposed payment details of ~1.2% of Plus subscribers active in a 9-hour window. Multi-tenant isolation in AI apps - OpenAI documents that prompt caches are not shared between organizations. Multi-tenant isolation in AI apps
- Carlini et al. (2021) extracted hundreds of verbatim training sequences from GPT-2, including names, phone numbers and emails. Multi-tenant isolation in AI apps
- Anthropic released ~39k human red-team attacks (Ganguli et al., 2022), a public seed set for your own suite. Red teaming AI systems
- PAIR, an attacker LLM refining prompts against a target model, often finds a jailbreak in under 20 queries. Red teaming AI systems
- Rule of thumb: report attack success rate (ASR) per category per release; any open critical finding blocks launch. Red teaming AI systems
- Rule of thumb: re-run the automated suite on every model, prompt or tool change; upgrades can reopen fixed holes. Red teaming AI systems
- ~250 poisoned documents were enough to backdoor models from 600M to 13B parameters, regardless of size (Anthropic, UK AISI, Turing Institute, Oct 2025). Model & data supply chain
- Poisoning 0.01% of LAION-400M via expired domains would have cost ~$60 (Carlini et al., 2023). Model & data supply chain
- A 2024 study found ~20% of packages suggested in LLM-generated code did not exist: names an attacker can register. Model & data supply chain
- PyTorch 2.6 (Jan 2025) made
torch.load(weights_only=True)the default. Model & data supply chain - OWASP LLM Top 10 (2026): LLM04 Supply Chain, LLM05 Data and Model Poisoning (LLM03 and LLM04 in the 2025 edition). Model & data supply chain
- InstructGPT (2022): outputs of the 1.3B RLHF model were preferred over those of the 175B GPT-3. Alignment & Constitutional AI
- 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. Alignment & Constitutional AI
- OpenAI rolled back a sycophantic GPT-4o update in April 2025, days after release. Alignment & Constitutional AI
- Four-fifths rule (US EEOC guidelines, 1978): a group's selection rate below 80% of the top group's signals adverse impact. Responsible AI: bias, fairness, transparency
- Gender Shades (2018): commercial gender classifiers erred up to 34.7% on darker-skinned women vs 0.8% on lighter-skinned men. Responsible AI: bias, fairness, transparency
- Model cards: Mitchell et al., 2019. Datasheets for datasets: Gebru et al., 2018. Responsible AI: bias, fairness, transparency
- 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. EU AI Act
- 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. EU AI Act
- Fines up to €35M or 7% of worldwide annual turnover for banned practices; up to €15M or 3% for most other breaches. EU AI Act
- GPAI models trained with more than 10²⁵ FLOPs are presumed to carry systemic risk. EU AI Act
- High-risk system logs: keep them at least 6 months, longer if other law requires. EU AI Act
- NIST AI RMF 1.0: released 26 Jan 2023; 4 functions, 7 trustworthiness characteristics. NIST AI RMF & ISO/IEC 42001
- NIST AI 600-1 Generative AI Profile (July 2024): 12 GenAI risk categories. NIST AI RMF & ISO/IEC 42001
- ISO/IEC 42001 (Dec 2023): Annex A lists 38 reference controls under 9 objectives (A.2–A.10). NIST AI RMF & ISO/IEC 42001
- ISO certification runs a 3-year cycle with annual surveillance audits. NIST AI RMF & ISO/IEC 42001
- AI RMF 1.0 is still the current version (Nov 2026); a revision ordered by the July 2025 US AI Action Plan has no public draft yet. NIST AI RMF & ISO/IEC 42001
AI Architecture
- Databricks data cited by BAIR (2024): 60% of LLM apps used some form of RAG, 30% used multi-step chains. Reference architecture of an LLM application
- Serial availability multiplies: a 99.9% app on a 99.5% model API is ≈ 99.4% without a fallback. Reference architecture of an LLM application
- Rule of thumb: the model call dominates latency and cost; a gateway should add only single-digit ms. Reference architecture of an LLM application
- Anthropic (2025): agents use ~4× the tokens of a chat interaction; multi-agent systems ~15×. Reference architecture of an LLM application
- OpenAI latency guide: halving output tokens can cut latency ~50%; halving the prompt often only ~1–5%. Quality, latency, cost: the AI trade-off triangle
- Price spread inside one family: GPT-4.1 $2 vs GPT-4.1-nano $0.10 per 1M input tokens (20×, 2025 list). Quality, latency, cost: the AI trade-off triangle
- RouteLLM (2024): ~85% cheaper than GPT-4-only on MT Bench at 95% of its quality. Quality, latency, cost: the AI trade-off triangle
- Batch APIs: ~50% off for results within 24 h. Anthropic cached input reads: ~0.1× base price. Quality, latency, cost: the AI trade-off triangle
- Nielsen's limits: ~0.1 s feels instant, ~1 s keeps the flow of thought, ~10 s loses attention. Quality, latency, cost: the AI trade-off triangle
- 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). Resilience: multi-provider failover & degradation
- 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. Resilience: multi-provider failover & degradation
- Google SRE: at most 3 attempts per request; keep retries under ~10% of a client's traffic. Resilience: multi-provider failover & degradation
- Anthropic postmortem (Sep 2025): a routing bug degraded up to 16% of Sonnet 4 requests in the worst hour, with no errors returned. Resilience: multi-provider failover & degradation
- Anthropic returns 429 for rate limits and 529 when overloaded; retry both with backoff. Resilience: multi-provider failover & degradation
- RFC 8693 (Jan 2020) defines OAuth token exchange; its
actclaim records who is acting for whom. Identity & authorization for agents - AWS STS role sessions last 15 min to 12 h, default 1 h; role chaining caps them at 1 h. Identity & authorization for agents
- Microsoft Entra access tokens default to a random 60–90 minute lifetime (75 on average). Identity & authorization for agents
- MCP spec: authorization is optional; HTTP servers that use it are OAuth 2.1 resource servers and must reject tokens not issued for them. Identity & authorization for agents
- Confused deputy: named by Norm Hardy in 1988, still the core agent-security bug. Identity & authorization for agents
- Anthropic prompt caching: reads ~0.1× base input; 5-minute default TTL refreshed on each hit, 1-hour option at a 2× write. Caching layers in an AI system
- OpenAI caches prompts automatically from 1,024 tokens; caches are not shared between organizations. Caching layers in an AI system
- Anthropic (2024): caching a 100k-token prompt cut time to first token from 11.5 s to 2.4 s. Caching layers in an AI system
- Semantic-cache threshold ~0.90–0.95 cosine (rule of thumb); tune it on labeled query pairs. Caching layers in an AI system
- Average latency = hit × cache + miss × origin: 30% hits at 5 ms vs 3 s misses ≈ 2.1 s. Caching layers in an AI system
- Anthropic: ≥60 days' notice before retiring a public model; Claude Sonnet 4.5 was deprecated Sep 30, 2026 and retires Nov 30, 2026. Model upgrades & deprecations
- OpenAI's stated minimums (2026): ≥6 months for GA models, ≥3 months for specialized variants, as little as ~2 weeks for previews. Model upgrades & deprecations
- Recent Claude snapshots were retired ~1–2 years after release (Sonnet 3.7: Feb 2025 → Feb 2026). Model upgrades & deprecations
- Same name, different behavior: GPT-4's prime-number accuracy went from 84% (March 2023) to 51% (June 2023) in Chen et al. Model upgrades & deprecations
- Rule of thumb: shadow for ≥1 week and canary at 1–5% for days, so weekly traffic patterns show up. Model upgrades & deprecations
- Cursor Tab (Sep 2025): online RL on accept/reject signals from 400M+ daily requests → 21% fewer suggestions, 28% higher accept rate. The data flywheel
- Tesla (Karpathy, CVPR 2021): 221 shadow-mode triggers and 7 data-engine loops built ~1M 10-second clips, ~6B labeled objects, 1.5 PB. The data flywheel
- GitHub Copilot study (Ziegler et al., 2022): acceptance rate predicted perceived productivity better than how long the code persisted. The data flywheel
- OpenAI API: customer data is not used for training by default since March 1, 2023. Check each provider's terms. The data flywheel
- Rule of thumb: reserve ~10% of the labeling budget for a random sample, so evals don't inherit the selection bias. The data flywheel
- 1B × 768 dims: float32 ≈ 3.07 TB, int8 ≈ 0.77 TB, binary or 96-byte PQ ≈ 96 GB. Vector search at billion scale
- 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. Vector search at billion scale
- Hugging Face (Mar 2024): binary quantization kept ~92.5% of retrieval quality, ~96% with rescoring; int8 kept ~97%. Vector search at billion scale
- Amazon S3 Vectors (GA Dec 2025): up to 2B vectors per index; under 1 s for infrequent queries, ~100 ms or less for frequent ones. Vector search at billion scale
- OpenAI (Jan 2024): text-embedding-3-large truncated to 256 dims still beat ada-002 at 1,536 dims on MTEB. Vector search at billion scale
- 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. On-device & edge inference
- Weights ≈ params × bits ÷ 8: 3B at 4-bit ≈ 1.5 GB; at 16-bit ≈ 6 GB, too much for most phones. On-device & edge inference
- Rule of thumb: decode tokens/s ≲ memory bandwidth ÷ weight bytes; ~50 GB/s ÷ 1.5 GB ≈ ~30 tokens/s. On-device & edge inference
- Apple's per-task LoRA adapters (rank 16) on the 3B model weigh tens of MB, so one base serves many features. On-device & edge inference
- Tesla HW3 (2019): two independent FSD chips, ~72 TOPS each, ~144 TOPS per computer. On-device & edge inference
AI System Design Cases
- 50-minute split: clarify 6 · estimate 4 · architecture 9 · deep dives 14 · eval 5 · safety 4 · serving 3 · failures 3 · close 2. The GenAI system design framework
- QPS = requests/day ÷ 86,400: 1M/day ≈ 12 QPS average; assume peak ≈ 2–3× average. The GenAI system design framework
- Tokens/day = requests × (input + output); output tokens cost ~4–8× input tokens on major APIs. The GenAI system design framework
- Chat latency budget (assumed): retrieval ~150 ms + rerank ~100 ms + first token ~0.5–1 s; stream the rest. The GenAI system design framework
- Batch APIs (OpenAI, Anthropic) cost ~50% less for work that can wait up to 24 h. The GenAI system design framework
- Corpus: 10M docs × ~4 chunks (assumed) = 40M chunks; 1,024-dim float32 ≈ 164 GB of vectors, ~41 GB at int8. Design: enterprise knowledge assistant
- Load: 50k employees × 40% daily active × 5 questions = 100k/day ≈ 3.5 QPS over 8 working hours, ~7 at a 2× peak. Design: enterprise knowledge assistant
- 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. Design: enterprise knowledge assistant
- First token: groups 20 ms (cached) + hybrid 120 ms + rerank 100 ms + prefill and queue ~700 ms ≈ 1 s. Design: enterprise knowledge assistant
- Full re-embed: 40M × 500 tokens = 20B tokens ≈ $400 at $0.02 per M; the real cost is the dual-index migration. Design: enterprise knowledge assistant
- Volume: 1M users × 0.3 contacts/month (assumed) ≈ 300k conversations/month ≈ 10k/day. Design: customer support agent
- LLM calls: 10k × ~6 = 60k/day; over 10 busy hours with a 2× peak, ~3–4 calls/s. Design: customer support agent
- Tokens: ~6k in per call (system, tools, history) × 6 ≈ 36k in + ~2k out per conversation → ~360M in + 20M out/day. Design: customer support agent
- Cost at an assumed $3/$15 per M: ~$1.1k + $0.3k ≈ $1.4k/day (~$42k/month) before caching; cache reads cost ~10–50% of input price, by provider. Design: customer support agent
- Stripe keeps idempotency keys for at least 24 h; retries that may land later need your own dedup table. Design: customer support agent
- 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. Design: ChatGPT-style assistant at scale
- Tokens: ~3k input (system + history + files) and ~400 output per message → 450B input + 60B output tokens/day. Design: ChatGPT-style assistant at scale
- 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. Design: ChatGPT-style assistant at scale
- Storage: 150M messages × ~1.5 KB ≈ 225 GB/day ≈ 80 TB/year before replication. Design: ChatGPT-style assistant at scale
- TTFT budget ~1 s: gateway 20 ms + history 20 + memory/file retrieval 80 + router 20 + queue and prefill ~500; safety runs in parallel. Design: ChatGPT-style assistant at scale
- Completion budget ~300 ms: debounce ~75 + network ~40 + prefill ~40 + 15 tokens × ~8 ms ≈ 275 ms (~7B FIM model, nearby region). Design: AI coding assistant
- Load: 100k seats × 40% typing at peak × 1 request per ~4 s after debounce ≈ 10k completion QPS. Design: AI coding assistant
- Prefill-bound: 10k QPS × ~2.6k input tokens ≈ 26M prefill tok/s vs ~200k output tok/s (~20 each), so prefix caching dominates. Design: AI coding assistant
- Agent task: 40 steps × ~30k context ≈ 1.2M input tokens ≈ $3.60 at an assumed $3/1M uncached, ~$0.70 with 90% cache hits at a 10% cache-read price, plus ~$0.30 output (~500/step at $15/1M). Design: AI coding assistant
- Index: 1M lines × ~10 tokens = 10M tokens ≈ 33k chunks of ~300 × 4 KB (1,024-dim float32) ≈ 135 MB; full re-embed ~$0.20 at $0.02/1M. Design: AI coding assistant
- Traffic: 30M searches/day ÷ 86,400 ≈ 350 QPS average; ×10 on a holiday evening ≈ 3.5k QPS, and every query hits every shard. Design: semantic product search
- Vectors: 50M × 768 dims × 4 B ≈ 154 GB in float32; int8 ≈ 38 GB + ~6 GB of HNSW links (M=16) per replica. Design: semantic product search
- p99 budget 200 ms: parse 15 + embed 10 + retrieval 60 + features 15 + ranking 30 + facets 20 + network/headroom 50. Design: semantic product search
- Query parses: 1M head queries × (300 in + 100 out) at an assumed $0.15/$0.60 per 1M ≈ $105 per full refresh, ~$50 via batch API; online for 30M searches/day = 30× the tokens + 300 ms. Design: semantic product search
- Re-embed: 50M products × ~100 tokens = 5B tokens ≈ $100 at $0.02/1M, or ~1 h on 16 GPUs at ~1k products/s each. Design: semantic product search
- Volume: 1M docs/month ≈ 33k/day ≈ 0.4/s; assume ~5× month-end peaks (~2/s) and 3 pages/doc → 3M pages/month. Design: document extraction pipeline
- 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. Design: document extraction pipeline
- 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. Design: document extraction pipeline
- OCR: at ~$1.50 per 1,000 pages, 3M pages ≈ $4.5k/month; if 60% are born-digital and skip OCR, ≈ $1.8k. Design: document extraction pipeline
- Review: assume 8% of docs flagged × ~60 s ≈ 1,330 h/month ≈ 8 FTE ≈ $33k at $25/h, ~90% of a total ≈ $0.04/doc. Design: document extraction pipeline
- Load: 100k items/min ≈ 1.7k/s; plan for ~3× peaks ≈ 5k/s; ≈ 4.3B items/month. Assume 80% text, 20% images. Design: content moderation system
- Funnel (assumed): hashes + classifiers settle ~97%; ~3% → LLM ≈ 50 req/s; ~0.05% → humans ≈ 72k items/day. Design: content moderation system
- 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. Design: content moderation system
- Self-hosted instead: an 8B guard model with prefix caching on ~4 GPUs (with headroom) at an assumed $2.50/GPU-hour ≈ $7k/month. Design: content moderation system
- Humans: 72k items/day × ~30 s ≈ 600 h/day ≈ 100 six-hour shifts/day ≈ ~140 reviewers on 5-day weeks. Design: content moderation system
- Inline budget: normalize ~5 ms + hash ~5 ms + classifiers ~20–50 ms → ≤ 100 ms p99. The LLM (0.5–2 s) and humans (minutes to hours) run async. Design: content moderation system
- Load: assume 2,000 users × 10 questions per workday = 20k/day; over ~8 working hours ≈ 0.7/s, peaks ~2/s. Design: text-to-SQL analytics assistant
- 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. Design: text-to-SQL analytics assistant
- 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. Design: text-to-SQL analytics assistant
- Warehouse guard: BigQuery on-demand is ~$6.25 per TiB scanned, so a full scan of a 10 TB table ≈ $57; a 50 GB per-query cap bounds the worst case at ~$0.30. Design: text-to-SQL analytics assistant
- Latency: retrieval ~0.2 s + generation 2–4 s + validation and dry run ~0.5 s + execution 1–5 s ≈ 4–10 s; each self-correction round adds ~3 s. Design: text-to-SQL analytics assistant
- Spider 2.0 (real enterprise schemas): the authors' code agent on o1-preview solved only ~21% of tasks, vs ~91% on Spider 1.0 and ~73% on BIRD (Lei et al., 2024). Design: text-to-SQL analytics assistant
- 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. Design: real-time voice agent
- 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?". Design: real-time voice agent
- 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. Design: real-time voice agent
- Concurrency: 100k calls/day × 4 min = 400k call-minutes; if ~15% land in the peak hour, 60k min ÷ 60 ≈ 1,000 concurrent calls. Design: real-time voice agent
- Cost per minute (assumed prices): telephony ~$0.01 + ASR ~$0.01 + TTS ~$0.02 + LLM ~$0.005 (3 turns × 3k tokens at $0.50/M) ≈ $0.05, vs ~$0.50 for a $30/h loaded human. Design: real-time voice agent
- 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. Design: internal AI platform
- 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. Design: internal AI platform
- Logs: 50M calls × ~10 KB (prompt, response, metadata) ≈ 500 GB/month; keep full payloads ~30 days and metadata 13 months. Design: internal AI platform
- Latency: auth + quota + routing under 10 ms p99; guardrail classifiers cost ~20–100 ms, so run low-risk input checks in parallel with the LLM call and cancel on a hit. Design: internal AI platform
- Routing math: moving 70% of traffic to a model 10× cheaper leaves 0.3 + 0.07 = 37% of spend, a ~63% cut, if evals show quality holds. Design: internal AI platform
- Full run: 500 tasks × 5 trials × ~30k tokens = 75M tokens ≈ $225 at an assumed $3/M blended; nightly ≈ $6.8k/month. Design: evaluation platform for agents
- Wall clock: 2,500 episodes × ~3 min ÷ 200 parallel sandboxes ≈ 38 min; the CI time budget sets the parallelism. Design: evaluation platform for agents
- 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. Design: evaluation platform for agents
- Reliability: 90% per trial gives pass^5 ≈ 59% (0.9^5); report pass^k next to the mean, because customers live in pass^k. Design: evaluation platform for agents
- Storage: ~150 KB per trajectory; 2,500 nightly + 50 PR runs × 180 ≈ 11.5k trajectories/day ≈ 1.7 GB/day ≈ 50 GB/month. Design: evaluation platform for agents
- 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. Design: LLM-powered recommendations
- 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. Design: LLM-powered recommendations
- 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. Design: LLM-powered recommendations
- ANN index: 10M items × 128-d float32 = 5.1 GB of raw vectors, which fits in RAM on one node: replicate for QPS instead of sharding for size. Design: LLM-powered recommendations
- Latency budget, p99 150 ms: features 20 + retrieval 15 + ranking 50 + re-rank 10 + network 25 + headroom 30. Design: LLM-powered recommendations
- 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. Design: review summarization with injection & PII defenses
- 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. Design: review summarization with injection & PII defenses
- 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. Design: review summarization with injection & PII defenses
- Backfill: 200M reviews ≈ 28B in + 12B out tokens ≈ $15k one-time at batch prices; 10M calls of 20 reviews = 200 batch files of 50k requests. Design: review summarization with injection & PII defenses
- Spot-check: 200 summaries/day (~0.2% of rewrites) at ~2 min each ≈ 7 reviewer-hours; 1,400 a week puts a 1% defect rate at ±0.5 points (95% CI). Design: review summarization with injection & PII defenses
- Traffic: 2B DAU × 10 feed loads/day (assumed) = 20B requests/day ≈ 230k QPS average, ~500k at a ~2× peak. Design: news feed ranking
- 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. Design: news feed ranking
- 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. Design: news feed ranking
- Latency p99 ~300 ms (assumed): candidates 50 + features 40 + first pass 20 + main pass 80 + final pass 20 + network and headroom 90. Design: news feed ranking
- Logs: 20B loads × ~20 viewed posts × ~2 KB of features ≈ 800 TB/day (assumed): downsample non-action impressions and reweight. Design: news feed ranking
- Scoring: 1M ad requests/s at peak (assumed) × 150 heavy-ranked ads = 150M predictions/s, each with pCTR and pCVR heads. Design: ads click-through prediction
- Training rows: 10B impressions/day × 1% CTR = 100M positives, plus 2.5% of 9.9B negatives ≈ 250M → ~350M rows/day (assumed volumes). Design: ads click-through prediction
- 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. Design: ads click-through prediction
- Embeddings: 5B hashed rows × 64 dims × 2 bytes (fp16) ≈ 640 GB → sharded across hosts for training and serving. Design: ads click-through prediction
- Facebook, 2014: trees + LR beat either alone by >3% NE; weekly instead of daily retraining cost ~1% NE; training on 10% of data cost ~1% NE. Design: ads click-through prediction
- Load: 5k payments/s at peak (assumed) × ~6 entities (card, device, IP, email, account, merchant) = ~30k key-value multi-gets/s. Design: real-time fraud detection
- Latency p99 ~100 ms (assumed): network 10 + features 15 + graph 10 + rules 5 + GBDT ~2 + policy 3 ms; logging async; ~55 ms headroom. Design: real-time fraud detection
- 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. Design: real-time fraud detection
- Base rate: at 0.1% fraud and 80% recall (assumed), a 1% false-positive rate declines ~12 good payments per fraud caught; Stripe reports Radar wrongly blocks ~0.1% of legitimate payments. Design: real-time fraud detection
- EU PSD2 transaction-risk-analysis exemption: PSP fraud rate ≤ 0.13% for ≤ €100, ≤ 0.06% for ≤ €250, ≤ 0.01% for ≤ €500; not available above €500. Design: real-time fraud detection
- 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. Design: deep research agent
- 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. Design: deep research agent
- 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. Design: deep research agent
- Wall clock: plan ~30 s + 2 research rounds × ~3 min + synthesis ~2 min + verification ~1 min ≈ 9–10 min, plus the user's time answering clarifications. Design: deep research agent
- Anthropic (Jun 2025): multi-agent research used ~15× the tokens of chat; token usage alone explained ~80% of performance variance on BrowseComp. Design: deep research agent
- 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. Design: AI answer engine (search + LLM)
- 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¢. Design: AI answer engine (search + LLM)
- 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. Design: AI answer engine (search + LLM)
- Search API: 10M/day × $5/1k ≈ $50k/day (~$18M/year), more than the small model's ~$30k/day: the build-vs-buy trigger for an own index. Design: AI answer engine (search + LLM)
- Liu et al. (2023), 4 generative search engines: 51.5% of sentences fully supported by citations; 74.5% of citations supported their sentence. Design: AI answer engine (search + LLM)
- 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. Design: LLM inference platform
- 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. Design: LLM inference platform
- 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). Design: LLM inference platform
- Unit cost: 1,500 tokens/s × 3,600 s = 5.4M output tokens per GPU-hour → ~$0.46 per M at 100% busy, ~$1.16 at 40%: utilization is the biggest cost lever. Design: LLM inference platform
- LoRA: rank 16 on every linear layer of Llama-3-70B ≈ 207M params ≈ 0.4 GB in BF16, ~0.3% of the base; hundreds fit in host RAM. Design: LLM inference platform
- 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. Design: data engine for autonomous driving
- 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. Design: data engine for autonomous driving
- Ingest: 100k clips/day × 1.5 GB = 150 TB/day ≈ 14 Gbps sustained, ~55 PB/year before tiering and expiry. Design: data engine for autonomous driving
- Training I/O: one pass over 1.5 PB at 1.6 TB/s (Tesla's 2021 NVMe tier) ≈ 16 min; at ~100 GB/s from object storage ≈ 4 h. Data loading, not FLOPs, can set epoch time. Design: data engine for autonomous driving
- Zero failures in n miles bounds the rate below ~3/n at 95% confidence; RAND (2016): ~275M failure-free miles to show a fatality rate no worse than the US human 1.09 per 100M miles. Design: data engine for autonomous driving
ML Foundations
- Expected squared error = bias² + variance + irreducible noise σ². Supervised learning, bias–variance & overfitting
- 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. Supervised learning, bias–variance & overfitting
- k = 5 or 10 folds; Kohavi (1995) recommended stratified 10-fold CV for model selection. Supervised learning, bias–variance & overfitting
- Test noise: at ~90% accuracy on 1,000 examples, the 95% confidence interval is about ±1.9 points. Supervised learning, bias–variance & overfitting
- 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). Loss functions & gradient descent
- LLaMA recipe: AdamW, weight decay 0.1, 2,000 warmup steps, cosine decay to 10% of peak LR, gradient clipping 1.0. Loss functions & gradient descent
- BERT fine-tuning grid: LR 5e-5, 3e-5 or 2e-5; batch 16 or 32; 2–4 epochs. Loss functions & gradient descent
- Mixed-precision Adam needs ~16 bytes per parameter (weights, grads, fp32 master + 2 moments): ~112 GB for 7B, before activations. Loss functions & gradient descent
- Original Transformer: 4,000 warmup steps, then LR decays ∝ 1/√step. Loss functions & gradient descent
- Dropout paper: keep hidden units with p 0.5–0.8 (drop 20–50%), inputs ~0.8; original Transformer: dropout 0.1. Regularization
- Label smoothing ε = 0.1 in Inception-v3 and the original Transformer. Regularization
- Weight decay: 0.1 with AdamW in LLM pretraining (GPT-3, LLaMA); 1e-4 with SGD in the ResNet recipe. Regularization
- Early-stopping patience of ~5–10 epochs is a common rule of thumb. Regularization
- Sigmoid's derivative peaks at 0.25: across 10 sigmoid layers the activation factors alone can shrink gradients to 0.25¹⁰ ≈ 10⁻⁶. Neural networks & backpropagation
- Training ≈ 6·N FLOPs per token (2N forward, ~4N backward), i.e. ~3× inference (Kaplan et al., 2020). Neural networks & backpropagation
- He init for ReLU: weight variance 2/fan_in; Xavier/Glorot: 2/(fan_in + fan_out). Neural networks & backpropagation
- Activation checkpointing recomputes activations instead of storing them: ~one extra forward pass (~33% more compute) for much less memory. Neural networks & backpropagation
- XGBoost paper (2016): 17 of the 29 Kaggle challenge-winning solutions published in 2015 used XGBoost. Gradient-boosted trees (GBDT)
- Grinsztajn et al. (NeurIPS 2022): on 45 datasets, trees still beat deep nets on medium-sized tabular data (~10K rows). Gradient-boosted trees (GBDT)
- 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. Gradient-boosted trees (GBDT)
- LightGBM (NeurIPS 2017) reported up to 20×+ faster training than conventional GBDT at almost the same accuracy. Gradient-boosted trees (GBDT)
- Facebook ads (He et al., 2014): boosted trees as feature transforms plus logistic regression beat either alone by over 3%. Gradient-boosted trees (GBDT)
- Kapoor & Narayanan: leakage affected ~300 published papers across 17 scientific fields (294 in the 2023 Patterns version). Feature engineering & data leakage
- Facebook ads (He et al., 2014): "the most important thing is to have the right features"; historical user and ad features dominated. Feature engineering & data leakage
- Rule of thumb: one-hot up to ~tens of categories; beyond that, target encoding, hashing or embeddings. Feature engineering & data leakage
- Rule of thumb (Google, TensorFlow feature columns): embedding size ≈ fourth root of the category count, e.g. 10,000 → 10. Feature engineering & data leakage
- scikit-learn's
TargetEncoder(≥ 1.3) cross-fits with 5 folds infit_transform, so no row's encoding sees its own label. Feature engineering & data leakage - Cost threshold (Elkan, 2001): t = c_FP / (c_FP + c_FN); a $5 review vs a $100 missed fraud gives t ≈ 0.048. Class imbalance & calibration
- Downsampling correction (He et al., Facebook, 2014): q = p / (p + (1 − p)/w), with w the negative sampling rate. Class imbalance & calibration
- Focal loss (Lin et al., 2017): γ = 2, α = 0.25 worked best for RetinaNet; γ = 0 is plain cross-entropy. Class imbalance & calibration
- scikit-learn: isotonic matches or beats sigmoid (Platt) with more than ~1,000 calibration samples. Class imbalance & calibration
- Facebook's calibration metric: average predicted CTR ÷ observed CTR; target ≈ 1.0. Class imbalance & calibration
- NDCG discount 1/log2(rank + 1): rank 1 = 1.0, rank 3 = 0.5, rank 10 ≈ 0.29. Learning to rank (LTR)
- An ensemble of LambdaMART rankers won Track 1 of the 2010 Yahoo! Learning to Rank Challenge (Burges, 2010). Learning to rank (LTR)
- MSLR-WEB30K benchmark: ~30K queries, 136 features per query–document pair, labels 0–4. Learning to rank (LTR)
- Rule of thumb: retrieve 100–1,000, rank with LTR, show 10–20. Learning to rank (LTR)
- XGBoost's
rank:ndcguses gain 2^rel − 1 by default, so labels must be ≤ 31. Learning to rank (LTR) - UCB1 bonus √(2 ln t / nᵢ) gives regret O(log T) (Auer et al., 2002); a fixed-ε greedy policy has linear regret. Exploration: multi-armed bandits
- Lai & Robbins (1985): no policy beats ~log T regret growth; UCB and Thompson sampling match that order. Exploration: multi-armed bandits
- LinUCB on Yahoo!'s front page: 12.5% click lift over a context-free bandit (Li et al., 2010). Exploration: multi-armed bandits
- Rule of thumb: ε = 5–10% for ε-greedy; Beta(1,1) prior for Thompson sampling on clicks. Exploration: multi-armed bandits
- AlexNet (2012): 15.3% top-5 ImageNet error vs 26.2% for the runner-up, the start of deep learning in vision. Computer vision: CNNs & Vision Transformers
- 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. Computer vision: CNNs & Vision Transformers
- ViT-B/16 at 224×224: 196 patch tokens (+1 [CLS]), ~86M params. Computer vision: CNNs & Vision Transformers
- Original YOLO: 45 FPS on a Titan X GPU; Fast YOLO: 155 FPS. Computer vision: CNNs & Vision Transformers
- Two stacked 3×3 convs see 5×5 and three see 7×7, with 27C² weights vs 49C² for one 7×7. Computer vision: CNNs & Vision Transformers
- CLIP: ~400M image–text pairs, batch 32,768, learned temperature initialized at τ = 0.07 (logit scale capped at 100). Contrastive learning & CLIP
- CLIP zero-shot ImageNet: 76.2% top-1, matching the original ResNet-50 without any of its 1.28M labeled training images. Contrastive learning & CLIP
- SimCLR: a batch of 8,192 gives 16,382 negatives per positive pair (two augmented views per image). Contrastive learning & CLIP
- Sentence-Transformers' MultipleNegativesRankingLoss is InfoNCE with in-batch negatives; default scale 20, i.e. τ = 0.05. Contrastive learning & CLIP
- DDPM trains with T = 1,000 noise steps; DDIM samples in tens of steps, 10–50× faster wall-clock (Song et al., 2020). Diffusion models
- Stable Diffusion v1: 512×512×3 → 64×64×4 latent (48× fewer values); ~860M-param U-Net plus a 123M CLIP text encoder. Diffusion models
- CFG costs 2 denoiser passes per step; the diffusers Stable Diffusion pipeline defaults to guidance 7.5. Diffusion models
- Distilled models (LCM, SDXL Turbo) sample in 1–4 steps; SDXL Turbo runs at 512×512 without CFG. Diffusion models
- Rule of thumb: cost per image ≈ steps × (2 with CFG) × one denoiser pass, which grows with resolution. Diffusion models
MLOps & ML Systems
- Google's maturity levels: 0 = manual, 1 = automated continuous training, 2 = CI/CD of the pipeline itself. The ML lifecycle
- Google's level-0 description: a new model version is deployed only a couple of times per year. The ML lifecycle
- Sculley et al. (NeurIPS 2015): ML code is only a small fraction of a real-world ML system. The ML lifecycle
- Rules of ML #1: don't be afraid to launch a product without machine learning. The ML lifecycle
- 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. LLMOps vs MLOps
- Batch APIs (OpenAI, Anthropic) cut price ~50% for jobs that can wait up to 24 h. LLMOps vs MLOps
- At n = 100 cases and a 50% pass rate, the 95% CI is about ±10 points: small eval sets can't see small regressions. LLMOps vs MLOps
- Rule of thumb: start a golden set with ~50–200 cases sampled from real traffic, then grow it from failures. LLMOps vs MLOps
- 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. Feature stores
- Point-in-time rule: use the latest value with feature_ts ≤ label_ts, and only if it is within the feature's TTL. Feature stores
- Uber's Michelangelo (2017) popularized the offline/online feature store split. Feature stores
- Google's Rules of ML #29: log the features used at serving and train on them; #32: reuse code between training and serving. Training–serving skew
- Rule of thumb: in a parity check, more than ~1% of rows disagreeing on a feature means a code-path bug, not noise. Training–serving skew
- 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. Training–serving skew
- PSI rule of thumb: <0.1 stable, 0.1–0.25 moderate shift, >0.25 significant shift worth acting on. Data drift & concept drift
- PSI is usually computed on 10 reference bins (deciles); empty bins need a small floor to avoid log(0). Data drift & concept drift
- Two-sample KS at n = m = 100k: D above ~0.006 is already significant at p < 0.05. Data drift & concept drift
- JS divergence is bounded in [0, 1] with log base 2; KL is asymmetric and infinite on empty bins. Data drift & concept drift
- Domain-classifier check: AUC ≈ 0.5 means reference and live data are indistinguishable. Data drift & concept drift
- 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. Model registry & versioning - Rule of thumb: keep the last 2–3 production versions loadable so rollback is instant. Model registry & versioning
- Rule of thumb: an LLM release pins ~5 things together: model snapshot, prompt, retrieval index, tool schemas, guardrail config. Model registry & versioning
- With 100 eval examples at ~80% accuracy, the 95% confidence interval is about ±8 points: a 2-point 'win' is noise. Experiment tracking & reproducibility
- Rule of thumb: compare model changes across 3–5 seeds and report mean ± std. Experiment tracking & reproducibility
- A reproducible run pins 4 things: code commit, data snapshot, environment digest, config with seeds. Experiment tracking & reproducibility
- PSI rule of thumb: < 0.1 stable, 0.1–0.25 moderate shift, > 0.25 significant shift. Monitoring models in production
- Rule of thumb: run LLM-as-judge on ~1–5% of production traffic, more right after a release. Monitoring models in production
- Google SRE: page when a 30-day SLO burns 2% of its error budget in 1 hour (14.4× burn rate). Monitoring models in production
- OpenAI Batch API and Anthropic Message Batches: 50% cheaper than synchronous calls, results within 24 h. Batch vs real-time inference
- Rule of thumb: an interactive page has ~100–200 ms end to end; the model gets only a slice of it. Batch vs real-time inference
- Kafka's default retention is 7 days (
log.retention.hours=168): your window to replay events into a backfill. Batch vs real-time inference - Covington et al. (YouTube, 2016): candidate generation narrows millions of videos to hundreds; ranking scores those to show dozens. Recommendation systems
- Netflix (Gomez-Uribe & Hunt, 2015): recommendations influence ~80% of hours streamed; the other ~20% comes from search. Recommendation systems
- 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). Recommendation systems
- Delta Lake defaults:
VACUUMkeeps 7 days of old files, the transaction log 30 days; older time travel needs an explicit snapshot. Data platform for AI - Target file sizes: Iceberg defaults to 512 MB, open-source Delta
OPTIMIZEto 1 GB (Databricks autotunes by table size); thousands of tiny files wreck scan speed. Data platform for AI - Origins worth knowing: Delta Lake came from Databricks, Iceberg from Netflix, Hudi from Uber. Data platform for AI
Distributed Systems
- L1 cache ~1 ns · main memory ~100 ns · SSD random read ~16–100 µs. Back-of-the-envelope estimation
- Round trip: same datacenter ~0.5 ms; California ↔ Netherlands ~150 ms. Back-of-the-envelope estimation
- 1 day = 86,400 s ≈ 10⁵ s, so 1M requests/day ≈ 12 QPS average. Back-of-the-envelope estimation
- 2¹⁰ ≈ 10³ (KB), 2²⁰ ≈ 10⁶ (MB), 2³⁰ ≈ 10⁹ (GB), 2⁴⁰ ≈ 10¹² (TB): thousand, million, billion, trillion. Back-of-the-envelope estimation
- Rule of thumb: 1 token ≈ 4 characters ≈ 0.75 English words. Back-of-the-envelope estimation
- Cloud Spanner multi-region SLA: 99.999% (~5 min/year): a CP system can still be highly available. CAP & PACELC
- Inter-continent round trip ~70–150 ms: the floor for an EC write that must reach another region. CAP & PACELC
- N=3 replicas: R=2, W=2 overlap (R + W > N); R=1, W=1 is the fast EL setting. CAP & PACELC
- Elasticsearch/OpenSearch default refresh interval: 1 s; new documents aren't searchable until then. CAP & PACELC
- Quorum rule: R + W > N; the usual setting is N=3, W=2, R=2. Consistency models
- DynamoDB reads are eventually consistent by default; a strongly consistent read costs 2× the read capacity. Consistency models
- Amazon S3 has been strongly read-after-write consistent since December 2020. Consistency models
- Spanner's TrueTime uncertainty (ε) ran ~1–7 ms in the 2012 paper; commit wait pauses for it before acknowledging a write. Consistency models
- Amazon Aurora: up to 15 read replicas, with lag typically under 100 ms (AWS docs). Replication
- RDS Multi-AZ (one standby) failover typically completes in 1–2 minutes. Replication
- Patroni's default leader-lock TTL is 30 s: roughly how long a dead leader goes unnoticed before promotion starts. Replication
- RF=3 is the common choice: with quorum 2, it survives losing one replica. Replication
- GitHub, Oct 2018: a 43 s network partition led to a cross-region failover and ~24 h of degraded service. Replication
- Going from
hash % Nto% (N+1)moves ~N/(N+1) of keys (~91% at N=10); fixed partitions or consistent hashing move ~1/(N+1). Partitioning & sharding - DynamoDB per-partition ceilings: 3,000 RCU, 1,000 WCU and 10 GB. Partitioning & sharding
- DynamoDB: 5 local and 20 global secondary indexes per table (default quota); GSIs are eventually consistent. Partitioning & sharding
- Instagram (2012) mapped several thousand logical Postgres shards onto far fewer physical servers. Partitioning & sharding
- Growing from N to N+1 nodes: consistent hashing moves ~1/(N+1) of keys,
% Nmoves ~N/(N+1). 10→11 is ~9% vs ~91%. Consistent hashing - Rule of thumb: with V vnodes per node, load spread ≈ 1/√V, so 100 vnodes ≈ 10% standard deviation. Consistent hashing
- Cassandra: 256 vnodes per node by default before 4.0, 16 since 4.0 (paired with a smarter token allocator). Consistent hashing
- Redis Cluster skips the ring: 16,384 fixed slots (CRC16 of the key mod 16384) assigned to nodes. Consistent hashing
- Bounded loads (Google, 2016): cap each node at (1+ε)× the average load; overflow walks clockwise to the next node. Consistent hashing
- 2f+1 nodes tolerate f failures: 3→1, 5→2, 7→3. Even sizes add cost, not tolerance. Consensus (Raft)
- 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. Consensus (Raft)
- etcd defaults: 100 ms heartbeat, 1,000 ms election timeout, 2 GB storage quota. Consensus (Raft)
- Raft paper: randomized election timeouts of 150–300 ms keep split votes rare. Consensus (Raft)
- Kafka 4.0 (2025) removed ZooKeeper; cluster metadata now lives in a KRaft (Raft) quorum. Consensus (Raft)
- Average latency = hit × cache + miss × origin: with 1 ms vs 50 ms, 90% hits → ~5.9 ms, 99% → ~1.5 ms. Caching strategies
- Origin load scales with the miss rate: going from 90% to 99% hits cuts backend traffic 10×. Caching strategies
- Latency ladder (Jeff Dean): RAM reference ~100 ns, same-datacenter round trip ~0.5 ms, disk seek ~10 ms. Caching strategies
- Rule of thumb: one Redis instance handles ~100k simple ops/s at sub-millisecond latency. Caching strategies
- Anthropic prompt-cache reads cost ~0.1× base input; the default TTL is 5 minutes, refreshed on each hit. Caching strategies
- Kafka default retention: 7 days (
log.retention.hours=168); compacted topics keep the latest value per key indefinitely. Queues vs streams (Kafka) - SQS visibility timeout: 30 s default, 12 h max; message retention 4 days default, 14 days max. Queues vs streams (Kafka)
- Kinesis shard: 1 MB/s or 1,000 records/s in, 2 MB/s out. Queues vs streams (Kafka)
- A consumer group's parallelism ≤ partition count; extra consumers sit idle. Queues vs streams (Kafka)
- Little's law for sizing: jobs in flight = arrival rate × time in system (50 jobs/s × 180 s = 9,000). Queues vs streams (Kafka)
- Stripe keeps idempotency keys for at least 24 hours; reusing a key with different parameters returns an error. Idempotency
- HTTP (RFC 9110): GET, HEAD, OPTIONS, TRACE, PUT and DELETE are idempotent; POST is not, and PATCH isn't guaranteed to be. Idempotency
- SQS FIFO deduplicates by
MessageDeduplicationIdwithin a 5-minute window: dedup windows are always bounded. Idempotency - A UUIDv4 key has 122 random bits: collisions are not a practical concern. Idempotency
- Full jitter: sleep = random(0, min(cap, base × 2^attempt)) — AWS Architecture Blog. Retries, backoff & circuit breakers
- Google SRE: at most 3 attempts per request, and a per-client budget keeping retries under 10% of requests. Retries, backoff & circuit breakers
- Retries multiply across layers: 3 layers × 4 attempts each = 4³ = 64 calls on the bottom service. Retries, backoff & circuit breakers
- OpenAI and Anthropic Python SDKs retry 2 times by default with exponential backoff (429, 5xx, connection errors). Retries, backoff & circuit breakers
- Anthropic returns 429 for rate limits (with a retry-after header) and 529 when the API is overloaded. Retries, backoff & circuit breakers
- HTTP 429 Too Many Requests is defined in RFC 6585; send Retry-After so clients know when to return. Rate limiting
- A fixed window can admit up to 2× the limit in a burst straddling the boundary. Rate limiting
- LLM providers limit RPM and TPM separately; Anthropic splits input (ITPM) and output (OTPM) tokens. Rate limiting
- Token bucket sizing: refill r = limit / 60 per second; capacity B = the largest burst you accept. Rate limiting
- N replicas each enforcing a local limit L give an effective limit of N × L. Rate limiting
- Queue wait ≈ depth ÷ service rate: 200 queued at 1,000 req/s is a 0.2 s wait. Backpressure & load shedding
- Google SRE: for steady traffic, keep the queue at 50% or less of the thread pool size. Backpressure & load shedding
- Google tags every request with one of four criticality levels: CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE. Backpressure & load shedding
- Google clients throttle themselves once their requests exceed K × the accepted ones; K = 2 is the usual choice. Backpressure & load shedding
- Metastable failures were named by Bronson et al. at HotOS 2021. Backpressure & load shedding
- 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. Load balancing
- Consistent hashing moves ~1/N of keys when one of N nodes leaves; hash mod N moves almost all of them. Load balancing
- Envoy outlier detection defaults: eject after 5 consecutive 5xx, 30 s base ejection, at most 10% of hosts. Load balancing
- LLM prefill cost spans ~500×: a 100k-token prompt vs a 200-token chat turn, before counting output. Load balancing
- Error budget per 30 days: 99% ≈ 7.2 h, 99.9% ≈ 43 min, 99.99% ≈ 4.3 min. SLIs, SLOs & error budgets
- 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%). SLIs, SLOs & error budgets
- At a 14.4× burn rate, a 30-day budget is gone in ~2 days (30 / 14.4 ≈ 2.1). SLIs, SLOs & error budgets
- Serial dependencies multiply: a 99.9% service on a 99.5% LLM API is ≈ 99.4% available without a fallback. SLIs, SLOs & error budgets
- AWS Well-Architected (checked Nov 2026): backup and restore = RPO hours, RTO up to a day; pilot light = RPO minutes, RTO tens of minutes. Disaster recovery (RPO & RTO)
- Same source: warm standby = RPO seconds, RTO minutes; multi-site active-active pushes both toward zero. Disaster recovery (RPO & RTO)
- Aurora Global Database (AWS, checked Nov 2026): asynchronous cross-region replication, typically under 1 s behind; a secondary is promoted in under a minute. Disaster recovery (RPO & RTO)
- DynamoDB global tables (checked Nov 2026): the default mode is asynchronous (RPO of a few seconds); the strong-consistency mode is synchronous (RPO 0) and needs exactly three regions. Disaster recovery (RPO & RTO)
- GitLab, Jan 2017: ~6 h of data lost and more than 18 h down after backups had been failing silently. Disaster recovery (RPO & RTO)
- DynamoDB: 400 KB max item; each partition serves up to 3,000 RCU and 1,000 WCU per second. SQL vs NoSQL
- MongoDB: 16 MB max document size. SQL vs NoSQL
- pgvector indexes (HNSW, IVFFlat) support up to 2,000 dimensions for
vector, 4,000 forhalfvec. SQL vs NoSQL - Postgres default isolation is Read Committed, not Serializable. SQL vs NoSQL
- Rule of thumb: pgvector on one well-sized node is comfortable up to ~10M vectors; beyond that, plan partitioning or a dedicated vector DB. SQL vs NoSQL
- Page size: 8 KB in Postgres, 16 KB in InnoDB; with hundreds of keys per page, B-trees stay ~3–4 levels deep. Database indexes: B-tree vs LSM
- Bloom filter: ~10 bits per key gives ~1% false positives (RocksDB's classic setting). Database indexes: B-tree vs LSM
- Postgres covering indexes (
INCLUDE) exist since v11; index-only scans need a vacuumed visibility map. Database indexes: B-tree vs LSM - Size-tiered compaction writes new SSTables while the old ones still exist, so in the worst case it needs free disk roughly equal to the data being compacted: keep ~50% headroom. Database indexes: B-tree vs LSM
- Kafka's default retention is 7 days (
log.retention.hours=168): an event store needs retention set to forever. Event sourcing & CQRS - Rule of thumb: snapshot a stream every ~100–1,000 events so loading never replays thousands. Event sourcing & CQRS
- Sagas were introduced by Garcia-Molina and Salem in 1987, for long-lived transactions in a single database. Sagas & the outbox pattern
- 2PC: two round trips with locks held throughout; a coordinator crash after PREPARE leaves participants blocked. Sagas & the outbox pattern
- Postgres keeps WAL for an unconsumed replication slot indefinitely unless
max_slot_wal_keep_size(PG 13+) caps it. Sagas & the outbox pattern - 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. Monolith vs microservices
- Availability compounds: 5 sequential dependencies at 99.9% each give ~99.5% end to end (0.999^5). Monolith vs microservices
- Amazon's two-pizza rule: a service is owned by a team small enough to feed with two pizzas. Monolith vs microservices
- Series count = product of label values: 50 routes × 5 status codes × 20 pods = 5,000 series; add
user_idwith 1M users and it's 5 billion. Observability: logs, metrics, traces - W3C
traceparentcarries a 16-byte trace-id and an 8-byte parent span-id. Observability: logs, metrics, traces - Google SRE's four golden signals: latency, traffic, errors, saturation. Observability: logs, metrics, traces
- Rule of thumb: head-sample ~1–10% of traces at high volume, but tail-sample to keep 100% of errors and slow requests. Observability: logs, metrics, traces
- Postgres RLS is skipped for superusers and
BYPASSRLSroles, and for the table owner unlessFORCE ROW LEVEL SECURITYis set. Multi-tenancy patterns - HTTP 429 Too Many Requests (RFC 6585) with
Retry-Afteris the standard reply to a tenant over its quota. Multi-tenancy patterns - Postgres logical replication supports row filters since v15: copy one tenant's rows out of the pool with
WHERE tenant_id = .... Multi-tenancy patterns - RFC 9110:
GET,HEAD,OPTIONSare safe; those plusPUTandDELETEare idempotent;POSTis not. API design: REST, gRPC, async - Go async past ~30 s: AWS API Gateway's integration timeout defaults to 29 s and ALB's idle timeout to 60 s. API design: REST, gRPC, async
- Stripe prunes idempotency keys after ≥24 h; a replay within that window returns the original result, even a 500. API design: REST, gRPC, async
- gRPC's default max receive message size is 4 MB: stream large payloads instead of raising it blindly. API design: REST, gRPC, async
OFFSET 500000 LIMIT 50reads and discards 500,000 rows; a keyset cursor (WHERE id > $1 ORDER BY id) seeks straight there via the index. API design: REST, gRPC, async- Origin load = requests × (1 − hit ratio): 95% hits → 5% reach the origin; 99% → 1%. CDNs and edge caching
- Fingerprinted assets:
Cache-Control: public, max-age=31536000, immutable(one year). CDNs and edge caching - CloudFront: first 1,000 invalidation paths a month free; a
/*wildcard counts as one path (checked Nov 2026). CDNs and edge caching - CloudFront without a cache policy uses a 24 h default TTL when the origin sends no
Cache-Control. CDNs and edge caching - S3 Standard: designed for 11 nines (99.999999999%) durability, data in at least 3 AZs. Object storage (S3-style)
- Multipart: parts of 5 MiB–5 GiB, at most 10,000; max object 50 TB since Dec 2025 (10,000 × 5 GiB). Object storage (S3-style)
- 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. Object storage (S3-style)
- us-east-1 list price (Nov 2026), per GB-month: Standard $0.023, Standard-IA $0.0125, Glacier Instant Retrieval $0.004; PUTs $0.005 per 1,000. Object storage (S3-style)
- Presigned URLs: up to 7 days with IAM user keys; with role credentials they expire with the session. Object storage (S3-style)
- Bloom: 1% false positives → ~9.6 bits/key and 7 hashes; 0.1% → ~14.4 bits/key and 10 hashes. Probabilistic data structures
- Bloom sizing: m = −n·ln p / (ln 2)² bits; optimal k = (m/n)·ln 2. Probabilistic data structures
- HyperLogLog standard error ≈ 1.04/√m; the paper counts beyond 10⁹ items at ~2% with 1.5 KB. Probabilistic data structures
- Redis HyperLogLog: up to 12 KB, 0.81% standard error, up to 2^64 items. Probabilistic data structures
- Count-Min: width w = ⌈e/ε⌉, depth d = ⌈ln(1/δ)⌉; overcount ≤ ε·N with probability 1−δ. Probabilistic data structures
- RocksDB tuning guide, 500 GB with 10× levels: write amp ~33, space amp ~1.14. Storage engines: LSM-tree vs B-tree
- Leveled compaction keeps ~90% of data in the last level, so space amp stays near 1.1×. Storage engines: LSM-tree vs B-tree
- Universal (size-tiered) compaction can temporarily double disk usage during a full compaction. Storage engines: LSM-tree vs B-tree
- B-tree pages: 8 KB in Postgres, 16 KB in InnoDB, written whole even for a 100-byte change. Storage engines: LSM-tree vs B-tree
- Facebook UDB on MyRocks: ~50% less storage than compressed InnoDB (2016). Storage engines: LSM-tree vs B-tree
- NTP accuracy: ~1 ms or better on a LAN, tens of ms over the public internet. Clocks and event ordering
- Spanner (2012): TrueTime ε is a ~1–7 ms sawtooth, ~4 ms most of the time; assumed drift 200 µs/s. Clocks and event ordering
- 200 µs/s of drift = 6 ms after 30 s, ~17 s after a day without sync. Clocks and event ordering
- CockroachDB max clock offset defaults to 500 ms; a node 80% of that off from half the cluster shuts down (docs, Nov 2026). Clocks and event ordering
- 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_threshold8 by default). Gossip protocols & failure detection - HashiCorp memberlist LAN defaults (checked Nov 2026): gossip to 3 nodes every 200 ms, probe one node every 1 s, 3 indirect probes. Gossip protocols & failure detection
- Dynamo paper (2007): each node contacts a random peer every second; gossiping the full membership works for a couple of hundred nodes. Gossip protocols & failure detection
- SWIM (2002): detection time and message load per member do not grow with group size; all-to-all heartbeats grow as N². Gossip protocols & failure detection
- Toy simulation, fanout 3: ~8 rounds for 1,000 nodes, 10–11 for 10,000, ~13 for 100,000. Gossip protocols & failure detection
- Redis lock:
SET key random NX PX 30000; release only if the value still matches (Lua script, orDELEXin Redis 8.4+). Distributed locks and fencing tokens - Redlock: N = 5 independent Redis masters, a majority of 3 needed; ~5–50 ms per-node timeout for a 10 s lease. Distributed locks and fencing tokens
- Kleppmann (2016): GC pauses have lasted minutes, and one GitHub incident delayed packets ~90 s, far past typical TTLs. Distributed locks and fencing tokens
- Redis expires keys by wall clock, not a monotonic clock, so a clock jump can free a lock early. Distributed locks and fencing tokens
- Bounded-out-of-orderness watermark ≈ max event time seen − allowed delay (e.g. 30 s). Stream processing: windows, watermarks, state
- Flink exactly-once sinks use two-phase commit since Flink 1.4 (Dec 2017), committing on each checkpoint. Stream processing: windows, watermarks, state
- Kafka Streams:
processing.guarantee=exactly_once_v2(Kafka 3.0+, brokers 2.5+). Stream processing: windows, watermarks, state - With transactional output, readers using
read_committedsee results only after the commit: latency ≥ checkpoint interval. Stream processing: windows, watermarks, state - Browsers: 6 SSE connections per domain over HTTP/1.1, shared by all tabs; HTTP/2 negotiates streams (default 100) (MDN). Real-time delivery: polling, SSE, WebSockets
- AWS ALB default idle timeout: 60 s. Send heartbeats more often or idle connections get cut. Real-time delivery: polling, SSE, WebSockets
- Discord (2017): ~5M concurrent users; guilds up to 30k concurrent users; big-guild publishes took 900 ms–2.1 s before Manifold. Real-time delivery: polling, SSE, WebSockets
- Slack (2023): tens of millions of connected clients; messages delivered worldwide in ~500 ms. Real-time delivery: polling, SSE, WebSockets
- Gateway sizing (assumption): 10M connections ÷ 100k per node ≈ 100 nodes, plus headroom to lose a zone. Real-time delivery: polling, SSE, WebSockets
- Geohash at the equator: 5 chars ≈ 4.9 × 4.9 km, 6 ≈ 1.2 km × 609 m, 7 ≈ 153 × 152 m. Geospatial indexing (geohash, S2, H3)
- H3: 16 resolutions, each with ~7× more cells; res 8 ≈ 0.74 km² (edge ~0.53 km), res 9 ≈ 0.1 km². Geospatial indexing (geohash, S2, H3)
- An H3 k-ring holds 1 + 3k(k+1) hexagons: 7 for k=1, 19 for k=2. Geospatial indexing (geohash, S2, H3)
- S2: 31 levels (0–30) of 64-bit cell ids; leaf cells are ~1 cm across. Geospatial indexing (geohash, S2, H3)
- Redis GEO: a 52-bit geohash as the sorted-set score; a radius query checks the 1 + 8 surrounding areas. Geospatial indexing (geohash, S2, H3)
- PKCE (RFC 7636, 2015): verifier of 43–128 chars; challenge = base64url(SHA-256(verifier)). AuthN vs AuthZ: sessions, JWT, OAuth
- RFC 9700 (OAuth security BCP, Jan 2025): public clients MUST use PKCE; the password grant MUST NOT be used. AuthN vs AuthZ: sessions, JWT, OAuth
- Amazon Cognito defaults (checked Nov 2026): access and ID tokens 1 hour, refresh tokens 30 days. AuthN vs AuthZ: sessions, JWT, OAuth
- Google Zanzibar (2019): trillions of ACLs, millions of checks/s, p95 under 10 ms. AuthN vs AuthZ: sessions, JWT, OAuth
- 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. Encryption & secrets management
- AWS KMS
Encrypttakes at most 4,096 bytes, so bulk data needs a data key fromGenerateDataKey. Encryption & secrets management - AWS KMS automatic rotation (checked Nov 2026): every 365 days by default, configurable from 90 to 2,560 days; old key material is kept. Encryption & secrets management
- OWASP Password Storage Cheat Sheet (checked Nov 2026): Argon2id with at least 19 MiB of memory, 2 iterations, parallelism 1; legacy bcrypt at work factor 10 or more, 72-byte limit. Encryption & secrets management
- AWS STS role credentials (checked Nov 2026) last from 15 minutes to 12 hours, 1 hour by default. Encryption & secrets management
- Google SRE: roughly 70% of outages are due to changes in a live system. Deployment strategies (canary, blue-green, flags)
- Kubernetes rolling update defaults:
maxSurge25% (rounded up),maxUnavailable25% (rounded down). Deployment strategies (canary, blue-green, flags) - SRE workbook example: a change failing 20% of requests behind a 5% canary costs ~1% of all requests. Deployment strategies (canary, blue-green, flags)
- CrowdStrike (Jul 2024): one content update crashed ~8.5M Windows devices (Microsoft's estimate); its remediation plan added canary, staged rollouts. Deployment strategies (canary, blue-green, flags)
System Design Classics
- Writes: 100M links/day (assumed) ÷ 86,400 s ≈ 1.2k/s; at 100:1 reads ≈ 116k redirects/s average. Design: URL shortener
- Key space: 62^6 ≈ 56.8B, 62^7 ≈ 3.5T; at 100M/day, 6 characters last ~1.6 years, 7 last ~96 years. Design: URL shortener
- Storage: 5 years ≈ 180B links × ~500 B ≈ ~90 TB before replication. Design: URL shortener
- Hash truncated to 7 base62 characters: ~50% chance of a collision after only ~2.2M links. Design: URL shortener
- Snowflake IDs (41-bit time, 10-bit machine, 12-bit sequence) are 64-bit integers: up to 11 base62 characters. Design: URL shortener
- Memory (assumed): 10M active keys × ~100 B per counter ≈ ~1 GB. Counter memory is rarely the constraint. Design: distributed rate limiter
- Throughput: 100k checks/s (assumed) is about one Redis instance's ~100k simple ops/s (rule of thumb): shard by client key. Design: distributed rate limiter
- Cloudflare (2017): its sliding-window counters wrongly allowed or limited only 0.003% of 400M requests. Design: distributed rate limiter
- Envoy's rate-limit filter: 20 ms default timeout; on errors it lets traffic through unless
failure_mode_denyis set (then 500). Design: distributed rate limiter - N regions with independent counters: worst case N × the limit; with a static split, a one-region client gets 1/N. Design: distributed rate limiter
- Reads: 300M DAU × 10 loads/day (assumed) = 3B/day ≈ 35k/s average, ~70k at a 2× peak. Design: news feed
- Push: 150M posts/day × 200 followers (assumed) = 30B feed inserts/day ≈ 350k/s, 10× the read rate. Design: news feed
- Feed cache: 300M users × 800 IDs × 8 B ≈ 1.9 TB of raw IDs; scores, Redis overhead and replicas multiply it. Design: news feed
- Twitter (2013): ~300k QPS timeline reads, ~5k tweets/s average, 800-entry Redis timelines, 3 replicas. Design: news feed
- Celebrity push at Twitter (2013): one tweet to ~31M followers took up to 5 minutes. Design: news feed
- Traffic: 100M DAU × 50 messages/day (assumed) = 5B/day ≈ 58k msg/s average, ~120k at a 2× peak. Design: chat system
- Storage: 5B × ~200 B ≈ 1 TB/day, ~365 TB/year before replication. Design: chat system
- Connections: ~30M concurrent ÷ ~100k per gateway (both assumed) ≈ 300 gateways. Design: chat system
- Discord (2023): 177 Cassandra → 72 ScyllaDB nodes; p99 history reads 40–125 ms → 15 ms. Design: chat system
- Discord (2017): ~10-day buckets per channel keep each partition under 100 MB. Design: chat system
- Volume: 100M users × 10 notifications/day (assumed) = 1B/day ≈ 12k/s average; campaigns spike far above. Design: notification system
- Dedup keys: 1B/day × ~100 B ≈ 100 GB per day of TTL; a 7-day TTL ≈ 700 GB. Design: notification system
- APNs: payload ≤ 4 KB (VoIP 5 KB); stores an undeliverable push up to 30 days. Design: notification system
- FCM: TTL 0–28 days; 4 collapse keys per device; Android discards all after 100 pending non-collapsible messages. Design: notification system
- Gmail bulk senders (5,000+/day, since Feb 2024): SPF, DKIM, DMARC, one-click unsubscribe, spam rate under 0.3%. Design: notification system
- Traffic: 100M DAU × 10 searches × ~6 requests (assumed) = 6B/day ≈ 70k QPS, ~140k at peak. Design: search autocomplete (typeahead)
- Budget: ~100 ms keystroke-to-render feels instantaneous (Nielsen, 1993); the network uses most of it. Design: search autocomplete (typeahead)
- Memory: ~100M prefixes × top 10 × 4-byte IDs ≈ 4 GB plus keys (assumed): replicate, don't shard. Design: search autocomplete (typeahead)
- Facebook (2010): more than 100 ms to retrieve a result makes typeahead "stutter". Design: search autocomplete (typeahead)
- Throughput: 1B pages/month ÷ ~2.6M s ≈ ~400 pages/s (assumption); plan ~800/s for a 2× peak. Design: web crawler
- Common Crawl, Aug 2026: 2.14B pages, 360 TiB uncompressed, ~185 KB per page. Design: web crawler
- Bloom filter: ~9.6 bits per item at 1% false positives, so 10B URLs ≈ 12 GB. Design: web crawler
- RFC 9309: cache robots.txt ≤ 24 h, parse ≥ 500 KiB, 5xx means assume complete disallow. Design: web crawler
- Near-duplicates: 64-bit SimHash with ≤ 3 differing bits suits 8B pages (Google, WWW 2007). Design: web crawler
- Dynamo (2007): common (N, R, W) = (3, 2, 2); example SLA 300 ms at p99.9 for 500 requests/s. Design: distributed key-value store
- Divergence is rare: 99.94% of shopping-cart reads saw exactly one version over 24 h. Design: distributed key-value store
- Dynamo truncates vector clocks at ~10 (node, counter) pairs; Cassandra stores hints only for a node's first 3 h down (default). Design: distributed key-value store
- Sizing: assume 10B keys × 1 KB × 3 replicas = 30 TB; at ~1 TB per node (assumed), ~30 nodes plus headroom. Design: distributed key-value store
- Redis Cluster: 16,384 slots, slot = CRC16(key) mod 16384; suggested maximum of ~1,000 nodes. Design: distributed cache
- Memcached defaults: 64 MB of memory, 1 MB max item, 4 threads, port 11211; keys are limited to 250 bytes. Design: distributed cache
- Redis defaults: no memory limit,
noeviction, and 5 keys sampled per eviction. Design: distributed cache - Sizing (assumed): 240 GB ÷ 24 GB usable per 32 GB node = 10 primaries, 20 nodes with replicas; 500k ops/s ÷ 10 = 50k each. Design: distributed cache
- Lose 1 of 10 nodes at a 95% hit rate: database load goes from 5% to 14.5% of reads, 2.9×. Design: distributed cache
- Egress: assume 100M views/day × 5 min × ~3 Mbps → ~11 PB/day, ~1 Tbps average. Design: video streaming platform
- Apple's example H.264 ladder: 145 kbps (416×234) to 7,800 kbps (1080p); 9 rungs sum ~25.6 Mbps. Design: video streaming platform
- Apple HLS spec: ~6 s target segment duration, a keyframe every 2 s. Design: video streaming platform
- S3 multipart (Nov 2026): up to 10,000 parts of 5 MiB–5 GiB; objects up to 48.8 TiB. Design: video streaming platform
- Buffer-based ABR cut Netflix rebuffers 10–20% vs its default algorithm (SIGCOMM 2014). Design: video streaming platform
- Assume 1M online drivers × 1 ping / 4 s ≈ 250k location writes/s at peak. Design: ride hailing (Uber, Lyft)
- H3 average cell: res 8 ≈ 0.74 km² (edge ~530 m); res 9 ≈ 0.105 km² (edge ~200 m). Design: ride hailing (Uber, Lyft)
- A hex disk of radius k covers 1 + 3k(k+1) cells: 7 for k = 1, 19 for k = 2. Design: ride hailing (Uber, Lyft)
- Rule of thumb: one Redis instance handles ~100k simple ops/s, so shard the geo index by region. Design: ride hailing (Uber, Lyft)
- Load (assumed): 100M daily users × 5 searches ÷ 86,400 s ≈ ~5.8k searches/s on average. Design: proximity service (Yelp)
- Geohash cells at the equator: 4 characters ≈ 39.1 × 19.5 km, 5 ≈ 4.9 × 4.9 km, 6 ≈ 1.2 km × 609 m. Design: proximity service (Yelp)
- Each geohash character adds 5 bits: one character less is a 32× larger cell. Design: proximity service (Yelp)
- Geo index (assumed): 200M entries × ~30 B ≈ ~6 GB, small enough to keep entirely in memory. Design: proximity service (Yelp)
- S2 average cell area: level 12 ≈ 5.07 km², level 13 ≈ 1.27 km², level 14 ≈ 0.32 km². Design: proximity service (Yelp)
- Assume 10M payments/day ≈ ~115/s average; plan ~10× for peak sales events. Design: payment system
- Stripe API v1 (Nov 2026): idempotency keys up to 255 chars, prunable after ≥ 24 h. Design: payment system
- Stripe retries webhooks for up to 3 days in live mode, with no ordering guarantee (Nov 2026). Design: payment system
- Handling raw card numbers can mean 300+ PCI DSS security controls (Stripe's guide, Nov 2026). Design: payment system
- Ledger volume: 10M payments × ~4 entries ≈ 40M rows/day, ~15B/year (assumption). Design: payment system
- Sizing (assumed): 10k transfers/s × 2 local writes ÷ ~1k writes/s per node ≈ 20 shards. Design: digital wallet
- With S shards, a transfer stays on one shard with probability 1/S: 20 shards means ~95% cross-shard. Design: digital wallet
- Ledger volume: 4 entries per transfer, so 10k transfers/s ≈ 40k entries/s at peak. Design: digital wallet
- PostgreSQL ships with 2PC off:
max_prepared_transactionsdefaults to 0. Design: digital wallet - Stripe's Ledger (2024): ~5 billion events a day; 99.99% of dollar volume ingested and verified within four days. Design: digital wallet
- Demand (assumed): 2M fans for 50k seats = 40 fans per seat; at ~4 seats per order, ~99% leave without tickets. Design: ticket booking
- Orders: 50k seats ÷ ~4 per order ≈ 12.5k orders; selling out in 10 min is only ~21 orders/s. Design: ticket booking
- Waiting room (assumed 2k admits/min): the last of 2M fans would wait ~1,000 min (~17 h), so announce sold-out early. Design: ticket booking
- Ticketmaster, Eras Tour presale (Nov 2022): 3.5B system requests, 4× its previous peak; 2M+ tickets sold that day. Design: ticket booking
- Cloudflare Waiting Room has two main knobs: total active users and new users per minute (checked Nov 2026). Design: ticket booking
- Load (assumed): 1M concurrent editors × ~1 batched op/s ≈ 1M ops/s in; at ~3 editors per doc, ~2M broadcasts/s out. Design: collaborative editor
- Log volume (assumed ~100 B per op): 1M ops/s ≈ 100 MB/s at peak; compact old ops into snapshots. Design: collaborative editor
- Snapshot every ~1,000 ops (assumed): opening a doc replays at most ~1,000 ops on top of it. Design: collaborative editor
- Google Docs: up to 100 people with view, edit or comment access can work in a file at once (checked Nov 2026). Design: collaborative editor
- Load (assumed): 100M runs/day ≈ 1.2k/s; if 20% fire in the first minute of each hour, that minute sees ~14k/s (~12×). Design: distributed job scheduler
- Lease (assumed): 30 s with a heartbeat every 10 s; a crashed worker's run restarts within ~30 s. Design: distributed job scheduler
- SQS visibility timeout, the same lease idea: 30 s by default, at most 12 h (checked Nov 2026). Design: distributed job scheduler
- Dropbox's ATF served ~9k async tasks scheduled per second, with at-least-once execution (Nov 2020). Design: distributed job scheduler
- Retries (assumed): backoff of 1, 2, 4, 8, 16 min spans ~31 min before the dead-letter queue. Design: distributed job scheduler
- Commits (assumed): 50M DAU × 10 changes/day = 500M/day ≈ 5.8k/s average, ~12k/s at a 2× peak. Design: file sync (Dropbox)
- Upload (assumed ~200 KB of new data per change after dedup): 500M × 200 KB ≈ 100 TB/day into block storage. Design: file sync (Dropbox)
- Dropbox: 4 MB blocks hashed with SHA-256 (2014); Magic Pocket stored multiple exabytes (2016). Design: file sync (Dropbox)
- Notifications (assumed ~100k idle long-polls per server): 50M connected devices need ~500 servers. Design: file sync (Dropbox)
- Ingest (assumed): 10k hosts × 1,000 series ÷ 15 s ≈ 670k samples/s. Design: metrics and monitoring system
- Storage: 670k/s × 86,400 s × ~1.37 B ≈ 79 GB/day raw, ~29 TB/year before retention and downsampling. Design: metrics and monitoring system
- Gorilla (VLDB 2015): 16 B to ~1.37 B per point (12×); ~96% of timestamps compress to a single bit. Design: metrics and monitoring system
- Prometheus defaults: 2 h blocks, 15-day local retention, 1 m scrape and rule-evaluation intervals (checked Nov 2026). Design: metrics and monitoring system
- Thanos: 5 m resolution for blocks older than 40 h, 1 h for blocks older than 10 days. Design: metrics and monitoring system
- Assumed load: 1M messages/s × 1 KB ≈ 1 GB/s ≈ 86 TB/day; 7 days × 3 replicas ≈ 1.8 PB. Design: distributed message queue
- Kafka defaults (4.4 docs, checked Nov 2026): 1 GiB segments, 7-day retention;
acks=alland the idempotent producer are defaults since 3.0 (Sept 2021, KIP-679). Design: distributed message queue - A follower leaves the ISR after 30 s behind the leader (
replica.lag.time.max.ms). Design: distributed message queue - Kafka design doc: linear writes ~600 MB/s vs ~100 kB/s random on a six-disk SATA array. Design: distributed message queue
- ISR survives f failures with f+1 replicas; a majority quorum needs 2f+1. Design: distributed message queue
- Assumed: 1B clicks/day ÷ 86,400 s ≈ 11.6k/s average, ~58k/s at a 5× peak. Design: ad click aggregator
- Raw log: 1B × ~0.5 KB (assumed) ≈ 500 GB/day. Design: ad click aggregator
- Dedupe state: ~42M click ids per hour of TTL (1B ÷ 24). Design: ad click aggregator
- Freshness ≈ 1-minute window + watermark delay (e.g. 30 s) + up to one checkpoint interval when the sink is transactional. Design: ad click aggregator
- Uber (2021): one-minute tumbling windows, Flink checkpoints every 2 minutes. Design: ad click aggregator
- Assumed: 1B events/hour ≈ 278k/s over 50M distinct items. Design: top-K and heavy hitters
- Space-Saving with m counters keeps every item above N/m occurrences; a count is at most N/m too high. Design: top-K and heavy hitters
- Count-min: w = ⌈e/ε⌉, d = ⌈ln(1/δ)⌉. With ε = 0.00001 and δ = 1%: 271,829 × 5 counters ≈ 11 MB at 8 B each. Design: top-K and heavy hitters
- Exact: 50M distinct items × ~100 B (assumed) ≈ 5 GB per window. Design: top-K and heavy hitters
- Elasticsearch
shard_sizedefault:size × 1.5 + 10terms per shard (checked Nov 2026). Design: top-K and heavy hitters ZADD,ZINCRBY,ZREVRANK,ZCOUNT: O(log N).ZSCORE: O(1). A range of M: O(log N + M). Design: real-time leaderboard- Assumed load: 5M DAU × 10 matches = 50M updates/day ≈ 580/s average, ~3k/s at peak. Design: real-time leaderboard
- Memory: 50M members × ~100 B (assumed) ≈ 5 GB, which fits one node. Design: real-time leaderboard
- Scores are doubles: integers are exact only up to 2⁵³ ≈ 9 × 10¹⁵. Design: real-time leaderboard
ZREVRANGEis deprecated since Redis 6.2; useZRANGE … REV(checked Nov 2026). Design: real-time leaderboard
Coding Interview Patterns
- ~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). Big-O and complexity analysis
- A modern CPU runs some hundreds of millions of simple operations per second; O(n²) at n = 10⁵ is 10¹⁰ steps. Big-O and complexity analysis
- log₂(10⁶) ≈ 20 and log₂(10⁹) ≈ 30: a log factor is cheap. Big-O and complexity analysis
- Python:
x in listandlist.pop(0)are O(n);x in setis O(1) average anddeque.popleft()is O(1). Big-O and complexity analysis - Python
dict/set: get, set, delete andinare O(1) average, O(n) worst case when keys collide. Hash maps, sets and prefix sums - Python salts
strandbyteshashes per process by default (since 3.3) to block hash-flooding denial of service. Hash maps, sets and prefix sums - Java 8
HashMapturns crowded buckets into balanced trees: worst case O(log n) instead of O(n) for comparable keys. Hash maps, sets and prefix sums - Two-sum: O(n²) brute force → O(n) time and O(n) space with a map. Hash maps, sets and prefix sums
- Build O(n), query O(1): q queries cost O(n + q) instead of O(n·q). Prefix sums and difference arrays
- 2D: build in O(rows × cols); any rectangle sum is 4 lookups. Prefix sums and difference arrays
- Difference array: O(1) per range update plus one O(n) pass: O(n + u) for u updates. Prefix sums and difference arrays
- Fenwick tree, for interleaved point updates and range sums: O(log n) each. Prefix sums and difference arrays
- The 2D form is the summed-area table (Crow, 1984), the "integral image" of Viola–Jones object detection (2001). Prefix sums and difference arrays
- Pair sum on sorted input: O(n) time, O(1) space; O(n log n) if you sort first. Two pointers
- 3Sum: O(n²) with sort plus two pointers, versus O(n³) brute force. Two pointers
- Floyd cycle detection: O(n) time and O(1) space, versus O(n) space for a visited set. Two pointers
- Merging two sorted arrays: O(n + m) with one pointer each. Two pointers
- O(n) time:
rightmoves n times andleftat most n times in total. Sliding window - Space O(k) for window counts, k = alphabet size or distinct values (26 for lowercase letters). Sliding window
- Brute force: O(n²) windows, O(n³) if each is rescanned. Sliding window
- Sliding-window minimum with a monotonic deque: O(n) total, versus O(n·k) rescanning each window. Sliding window
- log₂(10⁶) ≈ 20 and log₂(10⁹) ≈ 30 iterations. Binary search and search on the answer
- Search on the answer costs O(log(range) × cost of one check), e.g. O(n log(sum)). Binary search and search on the answer
- The
(low + high) / 2overflow bug sat in the JDK's binary search ~9 years before it was reported (Bloch, 2006). Binary search and search on the answer - That bug needs
low + high> 2³¹ − 1: arrays of 2³⁰ (~1 billion) elements or more. Binary search and search on the answer - Access and search O(n); insert or delete O(1) once you hold the previous node (any node, if doubly linked). Linked lists
- Reverse, find the middle, detect a cycle: O(n) time, O(1) space. Linked lists
- Merge two sorted lists of n and m nodes: O(n + m) time, O(1) extra space. Linked lists
- Python:
list.pop(0)andinsert(0, v)are O(n);collections.dequedoes both ends in ~O(1). Linked lists - Traversal: O(n) time. Space: O(h) for DFS (h = height), O(w) for BFS (w = widest level, up to ~n/2). Binary trees and BSTs
- Height: ~log₂ n when balanced (~20 for 10⁶ nodes), n when skewed like a linked list. Binary trees and BSTs
- BST search, insert, delete: O(h), so O(log n) balanced and O(n) skewed. Binary trees and BSTs
- A perfect tree with L levels has 2ᴸ − 1 nodes; the last level holds 2ᴸ⁻¹, about half. Binary trees and BSTs
- CPython's default recursion limit is 1,000 frames. Binary trees and BSTs
- Time O(n): each index is pushed once and popped at most once (≤ 2n operations). Stacks and monotonic stacks
- Space O(n) worst case: a strictly decreasing input never pops. Stacks and monotonic stacks
- Sliding window max: O(n) with a deque, O(n log n) with a lazy-deletion heap, O(n·k) brute force. Stacks and monotonic stacks
- Python:
list.pop()at the end is O(1),list.pop(0)is O(n); usecollections.dequefor both ends. Stacks and monotonic stacks - Push and pop O(log n); peek O(1);
heapifyO(n). Heaps and top-K - Top-K: O(n log K) time, O(K) space. Full sort: O(n log n) time, O(n) space. Heaps and top-K
- K-way merge of N total items from k lists: O(N log k). Heaps and top-K
- Quickselect: average O(n), worst case O(n²). Heaps and top-K
- Merge, meeting rooms, scheduling: O(n log n) for the sort, then O(n). Interval problems: sort and sweep
- Insert into an already sorted, disjoint list: O(n), no sort. Interval problems: sort and sweep
- Meeting rooms: 2n events; the answer is the peak of the running sum. Interval problems: sort and sweep
- Time O(V + E) with adjacency lists; O(V²) with an adjacency matrix. Graph traversal: BFS and DFS
- Grid R × C: R·C nodes and ≤ 4·R·C neighbor checks. Graph traversal: BFS and DFS
- Space O(V) for the visited set; the BFS queue holds up to the widest level. Graph traversal: BFS and DFS
- CPython's default recursion limit: 1,000 frames (
sys.getrecursionlimit()). Graph traversal: BFS and DFS - Time O(V + E); space O(V) for in-degrees and the queue. Topological sort
- Course schedule with n courses and p prerequisite pairs: O(n + p). Topological sort
- Longest path: O(V + E) on a DAG via topological order plus DP; NP-hard on general graphs. Topological sort
graphlib.TopologicalSorter: in Python's standard library since 3.9. Topological sort- Both optimizations: amortized O(α(n)) per operation; α(n) ≤ 4 for any realistic n (Tarjan, 1975). Union-Find (Disjoint Set Union)
- Union by rank alone: O(log n) per
find; rank never exceeds ⌊log₂ n⌋. Union-Find (Disjoint Set Union) - Kruskal's MST: O(E log E), dominated by sorting the edges. Union-Find (Disjoint Set Union)
- Space: O(n) for
parentandrank. Union-Find (Disjoint Set Union) - BFS: O(V + E). Dijkstra with a binary heap: O((V + E) log V). Shortest Paths (BFS, Dijkstra, Bellman-Ford)
- Bellman-Ford: O(V·E), V − 1 rounds plus one round to detect a negative cycle. Shortest Paths (BFS, Dijkstra, Bellman-Ford)
- DAG shortest paths: O(V + E) in topological order, negative weights allowed. Shortest Paths (BFS, Dijkstra, Bellman-Ford)
- 0-1 BFS: O(V + E), pushing 0-cost edges to the front of the deque. Shortest Paths (BFS, Dijkstra, Bellman-Ford)
- Floyd-Warshall, all pairs: O(V³) time, O(V²) space. Shortest Paths (BFS, Dijkstra, Bellman-Ford)
- Time = states × work per state: LCS and edit distance O(m·n); 0/1 knapsack O(n·W). Dynamic Programming
- Fibonacci: naive recursion ~O(2ⁿ) calls; memoized O(n). Dynamic Programming
- Two rolling rows cut edit distance memory from O(m·n) to O(min(m, n)). Dynamic Programming
- CPython's default recursion limit is 1,000 frames. Dynamic Programming
- Typical cost: O(n log n) for the sort, then O(n). Jump game: O(n) time, O(1) space. Greedy algorithms
- Coins {1, 3, 4}, amount 6: greedy uses 3 coins (4 + 1 + 1); the optimum is 2 (3 + 3). Greedy algorithms
- US coins without the nickel, {25, 10, 1}, for 40¢: greedy uses 7 coins; the optimum is 4 (4 × 10). Greedy algorithms
- Coin change by DP: O(amount × number of coin values). Greedy algorithms
- Subsets: 2ⁿ results, O(n·2ⁿ) with copying; n = 20 → 1,048,576 subsets. Backtracking
- Permutations: n! results; 10! = 3,628,800. Backtracking
- Combinations: C(n, k) = n! / (k!(n − k)!) results. Backtracking
- N-Queens: 92 solutions for n = 8 (12 up to rotation and reflection). Backtracking
- Recursion depth = number of decisions (≤ n), not the number of results. Backtracking
- insert, search, startsWith: O(L) for a key of length L, independent of the number of keys. Tries (Prefix Trees)
- Space: O(total characters) in the worst case, one node per distinct prefix. Tries (Prefix Trees)
- Array children: O(1) child lookup, but one slot per alphabet letter in every node (26 for a–z). Tries (Prefix Trees)
- Autocomplete: O(L) to reach the prefix node, plus the part of its subtree you visit. Tries (Prefix Trees)
- LRU cache:
getandputin O(1) average; space O(capacity). Design a data structure (LRU cache) - Min stack: push, pop, top and getMin in O(1); O(n) extra space for the stored minimums. Design a data structure (LRU cache)
- Random set: insert, remove and getRandom in O(1) average (hash map). Design a data structure (LRU cache)
- Python's
functools.lru_cachedefaults tomaxsize=128. Design a data structure (LRU cache) - Redis approximates LRU by sampling keys (
maxmemory-samples, default 5): a true LRU costs more memory. Design a data structure (LRU cache)
Staff/Principal Leadership
- Larson's archetypes: 4 — Tech Lead, Architect, Solver, Right Hand. What Staff/Principal actually means
- Rule of thumb: lead at most ~2–3 problems yourself at once; support the rest. What Staff/Principal actually means
- Rumelt's kernel has 3 parts: diagnosis, guiding policy, coherent actions. Writing a technical strategy
- Larson's recipe: 5 design docs → 1 strategy; 5 strategies, forecast 2 years out → 1 vision. Writing a technical strategy
- Rule of thumb: 2–4 pages gets read; the kernel itself should fit on one. Writing a technical strategy
- Rule of thumb: 2–6 pages; if it needs 20, split it into several docs. Design docs & RFCs
- Rule of thumb: about a week of async review, then a short decision meeting only if needed. Design docs & RFCs
- Rule of thumb: at least two real alternatives, one of them "do nothing". Design docs & RFCs
- Nygard (2011): 5 sections — title, status, context, decision, consequences. Architecture Decision Records (ADRs)
- Rule of thumb: 1–2 pages; anything longer is exploration that belongs in a design doc. Architecture Decision Records (ADRs)
- Bezos (2016): decide with ~70% of the information you wish you had; waiting for 90% is usually too slow. One-way vs two-way doors
- Type 1 / Type 2 decisions: Amazon's 2015 shareholder letter. One-way vs two-way doors
- Rule of thumb: compare TCO over ~3 years, including the people who run it, not just the first build. Build vs buy (and AI vendor selection)
- Rule of thumb: run the POC on a few hundred of your real cases, identical for every option. Build vs buy (and AI vendor selection)
- Rule of thumb: no decision-maker hears your proposal for the first time in the decision meeting. Influence without authority
- Rule of thumb: the proposal fits in 1–2 pages; details go in an appendix. Influence without authority
- Translate rates into counts: 95% accuracy at 10,000 requests a day is ~500 wrong answers a day. Communicating trade-offs to executives
- Rule of thumb: one page, 2–3 options, one explicit ask, one decision date. Communicating trade-offs to executives
- Rule of thumb: the first sentence must still work if it's the only one read. Communicating trade-offs to executives
- 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. Managing technical debt
- Rule of thumb: interest ≈ extra time per change × changes per month in that area. Managing technical debt
- Rule of thumb: reserve a fixed slice of every cycle (often 10–20%) for debt and maintenance. Managing technical debt
- Rule of thumb: build a shared platform capability when the second or third team needs it, not before. AI adoption strategy & roadmap
- Rule of thumb: no pilot starts without an owner, a baseline, an eval set and kill criteria. AI adoption strategy & roadmap
- Rule of thumb: score 1–5 per axis and multiply, so one weak axis sinks the total. AI adoption strategy & roadmap
- METR RCT (Jul 2025): 16 experienced OSS developers, 246 tasks, 19% slower with AI; they predicted 24% faster and afterwards believed 20% faster. Rolling out AI coding agents in an org
- GitHub RCT (Peng et al., 2023): the Copilot group finished an HTTP-server task 55.8% faster. Rolling out AI coding agents in an org
- 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. Rolling out AI coding agents in an org
- DORA 2024: a 25% rise in AI adoption was associated with ~1.5% lower delivery throughput and ~7.2% lower delivery stability. Rolling out AI coding agents in an org
- AGENTS.md, now stewarded by the Linux Foundation's Agentic AI Foundation, is used by 60k+ open-source projects. Rolling out AI coding agents in an org
- Batch APIs (OpenAI, Anthropic) bill asynchronous jobs at ~50% of the synchronous price, with up to 24 h turnaround. AI cost governance (FinOps for AI)
- Output tokens list at several times the input price on major APIs (4× and 5× are common), so output caps pay off early. AI cost governance (FinOps for AI)
- Forecast: monthly cost ≈ active users × calls per user × tokens per call × blended price per token. AI cost governance (FinOps for AI)
- Self-hosted: cost per token = GPU cost per hour ÷ tokens actually served per hour. Utilization is the whole game. AI cost governance (FinOps for AI)
- Rule of thumb: SEV1 stakeholder updates every 15–30 min, SEV2 every hour, even when the update is "no change". Incidents & blameless postmortems
- Rule of thumb: postmortem draft within about a week, while memory and logs are fresh. Incidents & blameless postmortems
- Track time to detect, time to mitigate and time to resolve separately; mitigation is the one users feel. Incidents & blameless postmortems
- Rule of thumb: delegate the problem, keep review of the one-way doors; agree which ones before work starts. Mentoring, coaching & sponsorship
- Rule of thumb: give SBI feedback within days, while the situation is still concrete for both of you. Mentoring, coaching & sponsorship
- Rule of thumb: 2–3 minutes per story, with Situation + Task under ~30 seconds. Behavioral interviews: STAR stories
- Story bank: 8–10 stories, each tagged with 2–3 competencies, including at least one real failure and one conflict. Behavioral interviews: STAR stories
- Rule of thumb: every Result carries a number, or a concrete before/after when no metric exists. Behavioral interviews: STAR stories
- Rule of thumb (Orosz): milestones small enough to finish in a few weeks; split longer ones. Leading cross-team projects
- Rule of thumb (Orosz): a written status update every week and a demo every week or two. Leading cross-team projects
- RACI and DACI both allow exactly one Accountable (or Approver) per decision. Leading cross-team projects
- Larson's migration playbook: de-risk, enable, finish; tooling migrates the easy ~90%, you finish the tail. Leading cross-team projects
- Cone of uncertainty: at the initial concept, actual effort can land ~0.25×–4× the estimate (Boehm, 1981; McConnell). Planning & estimation
- PERT expected value: (optimistic + 4 × likely + pessimistic) ÷ 6; long late tails pull it above "likely". Planning & estimation
- Evidence-Based Scheduling (Spolsky, 2007): tasks of 16 hours or less; simulate 100 futures from past estimate/actual ratios. Planning & estimation
- Brooks's law (1975): adding people to a late software project makes it later. Planning & estimation
- Ninety-ninety rule (Tom Cargill, Bell Labs): the last 10% of the code takes the other 90% of the time. Planning & estimation
- DORA 2024 elite cluster: on-demand deploys, lead time < 1 day, change fail rate ~5%, recovery < 1 hour. Engineering metrics (DORA)
- Clusters were re-derived from survey data each year; DORA 2025 replaced them with seven team archetypes. Engineering metrics (DORA)
- Five metrics since 2024 (rework rate added); in 2023, MTTR became failed deployment recovery time. Engineering metrics (DORA)
- SPACE (Forsgren et al., 2021): five dimensions; combine several and never read activity alone. Engineering metrics (DORA)
- Google's guide: respond within one business day at most. Code review
- Google's guide: ~100 lines is usually a reasonable change; ~1,000 is usually too large. Code review
- Google study (2018, 9M changes): median change of 24 lines, median of 1 reviewer, median review latency under 4 hours. Code review
- Same study: developers spent ~3 hours a week reviewing (mean 3.2, median 2.6). Code review
- Sackett et al. (2022) validity: structured interviews ~0.42, work samples ~0.33, unstructured interviews ~0.19. Hiring and structured interviews
- The older, still-quoted Schmidt & Hunter (1998) figures: structured 0.51, unstructured 0.38. Hiring and structured interviews
- Google re:Work: rejected candidates with a structured interview were 35% happier with the process. Hiring and structured interviews
- Amazon (2019): each hire should be better than 50% of would-be peers in similar roles. Hiring and structured interviews
- CD3 = cost of delay ÷ duration; the highest score goes first. Prioritization and saying no
- Black Swan Farming's worked example: CD3 order cut total delay cost 61% vs first-in-first-out ($69k → $27k). Prioritization and saying no
- RICE scales (Intercom, 2018): impact 3 / 2 / 1 / 0.5 / 0.25; confidence 100% / 80% / 50%; effort in person-months. Prioritization and saying no