RV·213C
Concepts to Revisit Forever III: Infrastructure, System Design, Frontend and AI
The roadmap's last four revision lists restated from first principles: Linux, Docker, networking and Kubernetes; requirements, capacity, bottlenecks, availability, caching, partitioning, replication and failure; the browser, CSS, JavaScript, accessibility, rendering, performance and security; probability, embeddings, attention, Transformers, RAG, evaluation, inference, agents and AI security; each with a prompt, the usual confusion and where to relearn it; with a lab that blocks Node's event loop, computes attention by hand and checks it against PyTorch, and shows why redundancy assumes independent failures.
Start here: the widest list
This chapter covers twenty-eight concepts, from the kernel to Transformers. They have one thing in common: each is a mechanism you can reason with, not a product you configure. Products change yearly (chapter 214 measures how fast); mechanisms don't.
Use the same routine as chapters 213A and 213B: heading first, explain from memory, read, answer the prompt, relearn if shaky.
Three mechanisms, measured
| Experiment | Result |
|---|---|
| a 10 ms timer in Node.js while one 200 ms synchronous loop runs | the timer fired 199 ms late |
| the same work in 40 chunks of 5 ms, yielding between them | at most 5.5 ms late |
| attention computed by hand (NumPy) vs PyTorch's built-in | identical to within 1 × 10⁻¹⁶ |
| dot products of random 512-dimensional vectors | spread (std) 22.8; after dividing by √512, 1.0 |
| 5 components in series, each 99.9% available | 99.5%: ~216 minutes down a month |
| each as a redundant pair (independent failures) | 99.9995% |
| the same pairs, with 30% of failures shared by both halves | 99.83% |
The event loop is single-threaded, attention's scaling keeps softmax usable, and redundancy is only as good as the independence of what fails.
How deep to go
Volume 17 defines six mastery levels. Hold these at L3 permanently. The ones on your specialization track (backend, frontend or AI) deserve L4–L5 and a deeper relearn each year.
Infrastructure
Linux
Everything is a process, a file descriptor or a mapping. Know how to see what's happening: processes (ps, top, /proc), files and sockets (lsof, ss), system calls (strace), memory (free, /proc/meminfo, page cache), disk (df, iostat), the network (ip, ss, tcpdump), logs (journalctl), and pressure stall information. Signals (SIGTERM politely, SIGKILL not), exit codes (137 = killed), permissions and capabilities, and the OOM killer.
Explain it: a service is slow; which five commands do you run first, and why? Relearn: Volume 6, chapter 79; Volume 1, chapter 08.
Docker
Containers are processes isolated with namespaces (what they can see: PIDs, mounts, network, users) and limited with cgroups (what they can use: CPU, memory, I/O), started from images (layered, content-addressed filesystems). Dockerfiles build images layer by layer, cached by instruction; order instructions from least to most frequently changing; use multi-stage builds, minimal bases, non-root users, and pin by digest.
Explain it: why does changing one line of source code rebuild only the last layers, and how can you ruin that? Relearn: Volume 6, chapters 80–81.
Networking in infrastructure
Every hop is a place for latency and failure: DNS resolution, load balancers (layer 4 by connection, layer 7 by request), NAT (connection tracking tables fill up), proxies and their timeouts and connection limits (Volume 19's lab ran nginx out of connections), TLS termination, MTU issues. In Kubernetes: pod IPs, Services (virtual IPs implemented by iptables/IPVS or eBPF), DNS names, Ingress or Gateway, and NetworkPolicies.
Explain it: trace a packet from a browser to a pod and name each component that could drop it. Relearn: Volume 6, chapters 82–83; Volume 7, chapter 87.
Kubernetes
A set of control loops that continuously move actual state toward declared desired state: you declare Deployments, Services, ConfigMaps; controllers create Pods, the scheduler places them on nodes by requests and constraints, kubelets run them and report health. Probes (startup, readiness, liveness), resource requests and limits, rolling updates, PodDisruptionBudgets, and RBAC are the concepts that matter in incidents.
Explain it: you kubectl delete pod and it comes back; which controllers did that, in what order? Relearn: Volume 6, chapters 83–84.
System design
Requirements
Functional requirements say what the system does; non-functional requirements say how well, as numbers: latency percentiles, availability, durability (RPO), recovery (RTO), scale, cost, security, compliance. Ask about users, journeys, read/write ratios, data growth, consistency needs, and what's explicitly out of scope. Design follows the numbers.
Explain it: turn "the app must be fast and reliable" into five testable requirements. Relearn: Volume 12, chapter 121; Volume 15.
Capacity
Estimate with simple arithmetic: requests per day ÷ 86,400 × peak factor; storage = items × size × retention × replication; bandwidth = requests × size. Know orders of magnitude: a database primary handles thousands of transactional writes per second, a cache instance ~100,000 simple operations per second, a modern server tens of thousands of simple HTTP requests per second. Then plan headroom (peak + a zone lost).
Explain it: estimate TiffinBox's daily API calls and peak rate from 50,000 subscribers. Relearn: Volume 12, chapter 122.
Bottlenecks
Throughput is limited by the first resource to saturate: CPU, memory, disk I/O, network, a lock, a connection pool, a single-threaded component, or a downstream service. Near saturation, queueing makes latency rise sharply (Little's law: concurrency = throughput × latency). Find bottlenecks by measuring utilisation and saturation of each resource (USE) under load, not by guessing.
Explain it: a service at 70% CPU has rising latency; name two other resources that could be the real bottleneck. Relearn: Volume 12, chapter 124; Volume 9, chapter 105.
Availability
The share of time (or requests) a system works. Components in series multiply their availabilities; redundancy improves it only when failures are independent (this chapter's lab). Remove single points of failure, spread across failure domains (zones), detect failure quickly, fail over automatically where safe, degrade gracefully, and practise recovery. Every extra nine costs roughly ten times more effort.
Explain it: why can adding a component for "high availability" lower availability? Relearn: Volume 12, chapter 125.
Caching at the design level
Decide where (client, CDN, service, database), what (whole responses, objects, computed results), and how fresh. Caches change the failure modes: if the cache is down, can the source survive the load? If the cache is wrong, how long until it heals? Cache hit rate depends on access skew (Volume 18's lab: a 1% cache served 75% of requests under Zipf traffic).
Explain it: design caching for a menu page and for a customer's order status; why do they differ? Relearn: Volume 12, chapter 126.
Partitioning at the design level
Partition when one node can't hold the data or the write load. Choose keys from the access pattern so most operations touch one partition; avoid hot keys; plan rebalancing (consistent hashing or many small virtual partitions); accept that cross-partition queries, joins and transactions become expensive.
Explain it: partition orders by customer or by kitchen; what does each choice make easy and hard? Relearn: Volume 12, chapters 124, 127.
Replication at the design level
Replicate for availability (failover), latency (copies near users) and read scale. Decide synchronous or asynchronous per data type, how to route reads (read-your-writes), how failover happens and how split brain is prevented, and how multi-region writes resolve conflicts (avoid them if you can: one home region per entity).
Explain it: why do most systems keep one writer per piece of data, even across regions? Relearn: Volume 12, chapters 127, 129, 134.
Failure
Everything fails: disks, nodes, zones, regions, dependencies, deploys, people. Design assumes it: timeouts, retries with budgets, circuit breakers, bulkheads, load shedding, idempotency, graceful degradation, and practised recovery. Partial failure (slow, not dead) is the hardest and most common. Failure exercises turn assumptions into evidence (Volume 19, chapters 212A–212B).
Explain it: why is a hung dependency worse than a dead one? Relearn: Volume 5, chapter 78; Volume 12, chapter 130.
Frontend
The browser
The browser fetches HTML, parses it into the DOM, fetches CSS (render-blocking) into the CSSOM, runs JavaScript (parser-blocking unless defer or async), and renders. It isolates sites (same-origin policy, site isolation in separate processes), caches aggressively, and runs JavaScript on one main thread shared with layout, painting and input handling.
Explain it: what does the browser do between receiving the first byte of HTML and the first paint? Relearn: Volume 2, chapters 12, 18.
CSS
A declarative system of rules: the cascade decides which declarations win (origin, specificity, order, layers), inheritance passes some properties down, and layout algorithms (normal flow, flexbox, grid, positioning) place boxes. Most "CSS is broken" moments are specificity, the box model (box-sizing), or not knowing which layout algorithm applies. Modern tools: custom properties, container queries, :has(), cascade layers, logical properties.
Explain it: why doesn't margin: auto centre an element vertically in normal flow but does in a flex container? Relearn: Volume 2, chapter 14.
JavaScript
Single-threaded execution with an event loop: run a task to completion, then all microtasks (promise callbacks), then possibly render, then the next task. async/await is syntax over promises, not threads; long tasks block everything (this chapter's lab). Closures capture variables, this depends on how a function is called, equality and coercion rules have traps, and modules scope code. Heavy work goes to Web Workers or is split into chunks.
Explain it: in what order do setTimeout(f, 0), Promise.resolve().then(g) and a synchronous console.log run? Relearn: Volume 2, chapters 15, 17.
Accessibility
Making interfaces usable by people with disabilities, which also makes them better for everyone. The browser builds an accessibility tree from semantic HTML; assistive technologies read it. Use native elements (buttons, links, labels, headings, landmarks), keep everything operable by keyboard with visible focus, provide text alternatives, sufficient contrast, and announcements for dynamic changes. ARIA fills gaps but can't fix wrong elements ("no ARIA is better than bad ARIA"). Test with tools and with real assistive technology.
Explain it: why is <div onclick> worse than <button> in at least four ways? Relearn: Volume 2, chapter 20.
Rendering
After style calculation, the browser does layout (computing geometry), paint (filling pixels into layers) and compositing (assembling layers, often on the GPU). Changing geometry triggers layout; changing colours triggers paint; changing transform and opacity can be composited only (cheap). Reading layout properties right after writing styles forces synchronous layout (layout thrashing). Frameworks add their own rendering (React's reconciliation) on top.
Explain it: why does animating left stutter while animating transform: translateX doesn't? Relearn: Volume 2, chapter 18.
Frontend performance
Measured by Core Web Vitals in the field: LCP (largest content painted: server time, render-blocking resources, image loading), INP (responsiveness: long tasks on the main thread), CLS (layout shift: unsized media, late-inserted content). Ship less JavaScript, split by route, load critical resources early, cache with hashed filenames, size images, and measure real users by release.
Explain it: a page has good Lighthouse scores but poor field INP; what's likely happening? Relearn: Volume 2, chapter 27.
Frontend security
Cross-site scripting (untrusted data executed as script: escape output, avoid innerHTML, use a Content Security Policy), cross-site request forgery (cookies sent automatically: SameSite, tokens, checking Origin), clickjacking (frame-ancestors), token theft (keep tokens out of JavaScript's reach: BFF and HTTP-only cookies), and supply-chain risk from npm dependencies.
Explain it: why does a strict CSP limit the damage of an XSS bug even if the bug exists? Relearn: Volume 2, chapter 28; Volume 10, chapter 108.
AI
Probability
Models output probabilities, and evaluation is statistics. Know: distributions, expectation and variance, conditional probability and Bayes' rule (base rates matter: a 99%-accurate test for a rare condition mostly flags false positives), independence (and its failure), the law of large numbers, sampling error (Volume 19's lab: 100 test questions catch a 5-point drop only a third of the time), and calibration (does 80% confidence mean right 80% of the time?).
Explain it: why does a classifier with 99% accuracy sometimes find almost nothing useful? Relearn: Volume 14, chapter 147.
Embeddings
Functions mapping items (words, sentences, images) to vectors so that similarity in meaning becomes closeness in space (cosine similarity). Learned by training on tasks that pull related items together and push unrelated ones apart. Used for retrieval, clustering, deduplication and classification. Limits: they capture what their training emphasised, are weak at exact matching (codes, names, negation), and change when you change the model (re-embed everything).
Explain it: why do hybrid search systems still use keyword matching alongside embeddings? Relearn: Volume 14B, chapter 159.
Attention
Each position computes a query; every position offers a key and a value. Scores are query–key dot products divided by √d (this chapter's lab shows why), turned into weights by softmax, and the output is the weighted sum of values. Causal masks stop a position seeing the future; multiple heads attend to different relations in parallel. Cost grows with the square of sequence length, which is why long contexts are expensive.
Explain it: write attention as a formula and explain each symbol. Relearn: Volume 14, chapter 154.
Transformers
Stacks of blocks, each with (multi-head) attention and a feed-forward network, with residual connections and layer normalisation; tokens enter as embeddings plus position information (absolute, or rotary in most current models). Decoder-only Transformers are trained to predict the next token; that single objective, at scale, produces language models. Training is parallel across positions; generation is sequential.
Explain it: why can Transformers train on a whole sequence at once but must generate one token at a time? Relearn: Volume 14, chapters 153–156.
RAG
Retrieval-augmented generation answers from your documents: ingest and chunk, embed and index, retrieve (hybrid, filtered), rerank, put the best passages in the prompt, generate with citations, and abstain when evidence is weak. Most failures are retrieval failures (the right passage wasn't found), so evaluate retrieval and generation separately.
Explain it: a RAG answer is wrong; how do you tell whether retrieval or generation failed? Relearn: Volume 14B, chapters 161–162.
Evaluation
AI systems are tested by datasets, not single examples: golden sets with labelled answers, metrics per component (retrieval recall, faithfulness, correctness, tool-call accuracy), enough examples to detect the changes you care about, paired comparisons between versions, human-calibrated judges, zero-tolerance checks for safety rules, and online monitoring after release.
Explain it: why must evaluation sets be large, and what's a paired comparison? Relearn: Volume 14B, chapter 175; Volume 19, chapter 211F.
Inference
Generating text runs prefill (process the prompt in parallel; drives time to first token) then decode (one token per forward pass, reusing the KV cache; memory-bandwidth-bound). Throughput comes from batching many requests (continuous batching); latency from smaller or quantised models, speculative decoding and shorter outputs. Cost scales with tokens; context length raises memory for the KV cache.
Explain it: why does doubling output length roughly double latency, but doubling prompt length doesn't? Relearn: Volume 14B, chapters 165–166, 179.
Agents
A loop in which a model chooses actions (tool calls), observes results and decides the next step until done. Useful when steps can't be known in advance; costly and harder to test than fixed workflows. Engineering essentials: a narrow tool set, validated arguments, permissions of the user, confirmations for consequential actions, step and budget limits, traces of every step, and evaluation on multi-step tasks.
Explain it: when is a fixed pipeline better than an agent, and why? Relearn: Volume 14B, chapters 169–171.
AI security
The model can be steered by any text it reads (prompt injection, direct and indirect), can leak what's in its context, and produces untrusted output. Defences live outside the model: least-privilege tools, user-scoped access, confirmations, output sanitising, isolation of untrusted content, rate and cost limits, and red-team evaluation sets. Supply chain (model and dataset provenance) and data protection apply as for any software.
Explain it: why can't "the system prompt tells the model to refuse" be your security boundary? Relearn: Volume 14B, chapter 176.
Lab: the event loop, attention by hand, and availability arithmetic
Setup. Node.js 22, NumPy and PyTorch on the lab machine.
Experiment 1: blocking Node's event loop
A setInterval asks for a tick every 10 ms and records how late each tick fires; after 100 ms, the main thread does some work; the run lasts 1.1 s.
| Work on the main thread | Ticks | Typical lateness (p50) | Worst lateness |
|---|---|---|---|
| none (idle) | 108 | 0.1 ms | 0.2 ms |
| one 200 ms synchronous loop | 89 | 0.1 ms | 199.3 ms |
the same 200 ms in 40 chunks of 5 ms, yielding with setTimeout(…, 0) |
104 | 0.2 ms | 5.5 ms |
JSON.parse of a 21 MB string (~140–200 ms of parsing) |
89 | 0.1 ms | 199.8 ms |
Experiment 2: causal attention by hand
Five positions, dimension 8: random inputs and projection matrices; scores QKᵀ/√d, a causal mask, softmax, then P·V, all in NumPy. Compared with PyTorch's scaled_dot_product_attention(…, is_causal=True): maximum difference 1.1 × 10⁻¹⁶. The weights:
position 0: [1.00 0.00 0.00 0.00 0.00]
position 1: [0.88 0.12 0.00 0.00 0.00]
position 2: [0.42 0.29 0.29 0.00 0.00]
position 3: [0.28 0.24 0.29 0.19 0.00]
position 4: [0.34 0.06 0.24 0.11 0.26]
Why divide by √d: dot products of 1,000 pairs of random vectors with standard-normal entries:
| d | Standard deviation of q·k | After ÷ √d |
|---|---|---|
| 8 | 2.84 | 1.00 |
| 64 | 8.35 | 1.04 |
| 512 | 22.79 | 1.01 |
Experiment 3: availability arithmetic
| Configuration | Availability | Downtime per 30 days |
|---|---|---|
| one component | 99.9% | 43 min |
| 5 components in series, each 99.9% | 99.501% | ~216 min |
| each component a redundant pair, independent failures (computed) | 99.9995% | ~13 s |
| the same pairs, simulated, with 30% of failures hitting both halves | 99.83% | ~73 min |
The last row is a simulation over 10,000 periods with a per-period failure probability of 0.1% per component, so it carries sampling noise; the expected value is about 99.85%.
What it shows
- One thread, one queue. Any long synchronous task, your loop or a library call like
JSON.parse, delays every timer, input event and render behind it. Chunking with yields kept the worst delay at one chunk's length. In browsers this is exactly what INP measures. - Attention is a few lines of linear algebra, and the √d scaling keeps scores in a range where softmax gives graded weights instead of near-one-hot ones, whatever the dimension.
- Series multiplies, redundancy multiplies only when independent. With correlated failures (a shared zone, deploy, configuration or dependency), the "redundant" system's downtime fell only to about a third of the unprotected system's (73 vs 216 minutes a month), instead of to seconds. Spread replicas across failure domains, stagger deploys, and don't share the thing that fails.
Try it yourself
- Move the
JSON.parseinto a Worker thread and rerun Experiment 1. - Remove the √d scaling at d = 512 and look at the softmax weights for a 50-position sequence.
- Add multi-head attention (2 heads of 4 dimensions) by hand and compare with
nn.MultiheadAttention. - Recompute Experiment 3 for 3 components in series where one of them is a single, non-redundant database.
Revision sheet: infrastructure, system design, frontend and AI concepts
One line each
- Linux: processes, descriptors, mappings; know the observation tools.
- Docker: namespaces see, cgroups limit, images are layers.
- Networking: every hop adds latency, limits and failure modes.
- Kubernetes: controllers reconcile actual to desired state.
- Requirements: numbers, not adjectives.
- Capacity: simple arithmetic plus headroom.
- Bottlenecks: the first resource to saturate; queueing near saturation.
- Availability: series multiplies; redundancy needs independence.
- Caching / partitioning / replication: design choices with failure modes.
- Failure: partial failure is the hard case; practise recovery.
- Browser: DOM, CSSOM, blocking resources, one main thread.
- CSS: cascade, box model, layout algorithms.
- JavaScript: event loop, tasks and microtasks; long tasks block.
- Accessibility: semantic HTML builds the accessibility tree; keyboard and announcements.
- Rendering: layout, paint, composite; animate transforms.
- Performance: LCP, INP, CLS in the field.
- Frontend security: XSS, CSRF, clickjacking, token theft, dependencies.
- Probability: base rates, sampling error, calibration.
- Embeddings: meaning as geometry; weak on exact matches.
- Attention: softmax(QKᵀ/√d)V; quadratic in length.
- Transformers: attention + MLP blocks; parallel training, sequential generation.
- RAG: retrieve, rerank, cite, abstain; evaluate retrieval separately.
- Evaluation: large sets, paired comparisons, zero-tolerance checks.
- Inference: prefill vs decode; batching; KV cache.
- Agents: loops with narrow tools, limits and confirmations.
- AI security: defences outside the model.
Numbers to remember
- Lab: 200 ms task → timer 199 ms late; 5 ms chunks → 5.5 ms; q·k spread 22.8 at d = 512 → 1.0 after ÷ √d.
- 0.999⁵ = 99.5% (~216 min/month); correlated pairs 99.83%.
Glossary
- Microtask: a promise callback, run after the current task before the next.
- Little's law: concurrency = throughput × latency.
- Failure domain: a set of components that can fail together.
- KV cache: stored keys and values from earlier tokens.
- Accessibility tree: the browser's semantic model exposed to assistive technology.