Specialization DepthVol. 17 · Part XVII
0 / 0

Trails / Specialization Depth

SD·194G

Breadth at L3/L4: Frontend, Angular, React, Search, NoSQL, GPU/ML

What internals-and-debugging depth means for a backend engineer in the six breadth topics, with experiments: why breadth at L3/L4 (not L1/L2) pays off; the front end as a backend engineer must understand it (the critical rendering path, caching, CORS, Core Web Vitals); React's reconciliation built in 60 lines of TypeScript, showing why list keys turn four DOM operations into one; Angular's change detection, zone.js and signals; search engines from first principles — an inverted index with BM25 that ranks exactly as rank_bm25 does, analysis, relevance and the L4 problems; NoSQL families and their data-modelling rule, and consistent hashing measured (80% of keys move with hash-mod-N versus 22% with a ring); and GPU/ML internals for the backend engineer: arithmetic intensity and the roofline (0.08 versus 341 FLOP per byte), why LLM serving is memory-bound (128 KiB of KV cache per token), batching, quantisation, and what to ask of ML teams.

18 topics · ~20 min read · 30-question quiz
Updated Suggest a correction

Start here: why breadth means L3/L4, not L1/L2

A backend specialist doesn't need to build React apps or train neural networks. But "I've heard of it" (L1) isn't enough either: you'll debug a slow page that's really an API problem, choose between PostgreSQL full-text search and Elasticsearch, or size GPUs for an inference service. Breadth topics are where you need L3/L4: understand the internals well enough to reason about behaviour and find problems, even if you don't work in that area daily.

Searching 106,920 text passages (this textbook's chapters, repeated) for "idempotency" in PostgreSQL:

Approach Time Matches
ILIKE '%idempotency%', no index 602 ms 2,660
same with a trigram index 24 ms 2,660
full-text search (stemmed words, GIN index) 3.2 ms 4,760
full-text, "idempotent keys" 1.7 ms 2,540 (ILIKE for the phrase: 0)

Full-text search was 190× faster and found more, because it matches word stems ("idempotent", "idempotency" and "idempotence" all become idempot) rather than exact characters. But stemming isn't spelling correction: the typo "idempotncy" found nothing with full-text search, while trigram similarity found 4,820 matches (slowly, in 742 ms). Knowing why each behaves this way (tokenising, stemming, inverted indexes, n-grams) is L3; choosing between them for a product is L4–L5.

How deep to go in the breadth topics

Volume 17 defines six mastery levels; for the breadth topics (frontend, Angular, React, search, NoSQL, GPU/ML) the targets are L3/L4:

Level You can…
L1 name the technology and what it's for
L2 make small changes or run it with guidance
L3 explain its internals: rendering and change detection, inverted indexes, NoSQL data models, GPU execution
L4 diagnose problems that cross into it from your own area and propose fixes
L5 (specialists) design systems around it
L6 (specialists) run it at scale

Why L3/L4 rather than L1/L2

The roadmap asks backend engineers for internals and debugging depth in these breadth topics, not just vocabulary. The reason is practical: the boundary between your system and these systems is where the hardest bugs live. A backend engineer at L2 in React can't tell whether a slow page is the API or the render; at L3/L4 they can open the performance panel, see that the API returned in 80 ms and the page then spent 900 ms re-rendering a 2,000-row list without keys, and say so with evidence. The same holds for search relevance complaints, hot partitions in DynamoDB, and GPU inference latency.

L3/L4 in a breadth topic means: you can explain its core mechanism, read its diagnostic tools, and hold a design conversation with the specialists. It doesn't mean you'd design its hardest parts alone (that's their L5/L6).

The front end, for a backend engineer

The minimum L3 model:

  • Critical rendering path: HTML is parsed into the DOM; CSS into the CSSOM; together they form the render tree; then layout (geometry), paint, and compositing. Synchronous scripts in <head> block parsing; CSS blocks rendering. A server-rendered page shows content before JavaScript runs; a client-rendered SPA shows nothing until its bundle downloads, parses and executes.
  • Caching across the boundary: Cache-Control, ETag, content-hashed assets, CDN behaviour (Volume 16, ch. 188); your API's cache headers decide what the browser and CDN can do.
  • CORS: the browser (not the server) enforces the same-origin policy; your API's Access-Control-Allow-* headers tell it which cross-origin reads to allow; preflight OPTIONS requests add a round trip for non-simple requests (custom headers, JSON content type). Access-Control-Allow-Origin: * with credentials is refused by browsers; reflecting any Origin with credentials is a vulnerability.
  • Core Web Vitals: LCP (largest content paint ≤ 2.5 s), INP (interaction to next paint ≤ 200 ms), CLS (layout shift ≤ 0.1) at the 75th percentile of real users; your API's latency feeds directly into LCP for data-driven pages.
  • L4 tools: the browser's Network panel (waterfall: DNS, connect, TLS, TTFB, download per request; HTTP/2 multiplexing), Performance panel (long tasks on the main thread), Lighthouse, real-user monitoring.

Typical L4 diagnosis at the boundary: "the page is slow" → waterfall shows a 1.2 s request chain (page → config → user → subscriptions → menu, each waiting for the previous). The fix is backend-shaped: an aggregated endpoint (backend-for-frontend), parallel requests, or server rendering with the data already embedded.

React at L3: reconciliation

React's core idea: components are functions from state to a description of the UI (the virtual DOM); when state changes, React re-runs them, diffs the new description against the previous one, and applies the minimal set of real DOM changes. The diff is heuristic, O(n) rather than the O(n³) of a general tree diff: elements of different types are replaced wholesale, and children lists are matched by key if keys exist, otherwise by index. A 60-line reconciler shows why keys matter:

TypeScript
// React's core idea in 60 lines: render() returns a description (virtual DOM); reconcile() diffs it against the
// previous one and emits the minimal DOM operations. Keys let the diff match list items that moved.
type VNode = { type: string; key?: string; props: Record<string, string>; children: (VNode | string)[] };
const h = (type: string, props: Record<string, string> = {}, ...children: (VNode | string)[]): VNode =>
  ({ type, key: props.key, props, children });

const ops: string[] = [];
function reconcile(path: string, prev: VNode | string | undefined, next: VNode | string | undefined): void {
  if (prev === undefined && next !== undefined) { ops.push(`INSERT ${path} ${describe(next)}`); return; }
  if (next === undefined && prev !== undefined) { ops.push(`REMOVE ${path}`); return; }
  if (typeof prev === "string" || typeof next === "string") {
    if (prev !== next) ops.push(`SET_TEXT ${path} "${next}"`);
    return;
  }
  if (prev!.type !== next!.type) { ops.push(`REPLACE ${path} ${describe(next!)}`); return; }   // different type: rebuild subtree
  for (const k of new Set([...Object.keys(prev!.props), ...Object.keys(next!.props)]))
    if (k !== "key" && prev!.props[k] !== next!.props[k]) ops.push(`SET_ATTR ${path} ${k}=${next!.props[k]}`);
  // children: match by key when present, else by index
  const keyed = next!.children.every((c) => typeof c !== "string" && c.key !== undefined);
  if (keyed) {
    const old = new Map(prev!.children.map((c) => [(c as VNode).key!, c as VNode]));
    next!.children.forEach((c, i) => {
      const n = c as VNode;
      if (old.has(n.key!)) { reconcile(`${path}/${n.key}`, old.get(n.key!), n); old.delete(n.key!); }
      else ops.push(`INSERT ${path}/${n.key} at ${i}`);
    });
    for (const k of old.keys()) ops.push(`REMOVE ${path}/${k}`);
  } else {
    const len = Math.max(prev!.children.length, next!.children.length);
    for (let i = 0; i < len; i++) reconcile(`${path}/${i}`, prev!.children[i], next!.children[i]);
  }
}
const describe = (n: VNode | string) => (typeof n === "string" ? `"${n}"` : `<${n.type}>`);

const menu = (items: string[], keyed: boolean) =>
  h("ul", {}, ...items.map((it) => h("li", keyed ? { key: it } : {}, it)));

for (const keyed of [false, true]) {
  ops.length = 0;
  reconcile("ul", menu(["Biryani", "Rajma", "Paneer"], keyed), menu(["Dal", "Biryani", "Rajma", "Paneer"], keyed));
  console.log(`${keyed ? "with keys   " : "without keys"} (${ops.length} ops): ${ops.join("; ")}`);
}
Text
without keys (4 ops): SET_TEXT ul/0/0 "Dal"; SET_TEXT ul/1/0 "Biryani"; SET_TEXT ul/2/0 "Rajma"; INSERT ul/3 <li>
with keys    (1 ops): INSERT ul/Dal at 0

Prepending one item without keys rewrites every existing item (and in real React would also mix up component state, such as an input's typed text, between rows); with stable keys, one insert. Using the array index as the key reproduces the unkeyed behaviour. Real React adds a fibre architecture (interruptible rendering work), batching of state updates, concurrent features, and (React 19, with the React Compiler) automatic memoisation; the L3 core is the diff above.

React L4 signatures: re-render storms (a context value recreated on every render; inline object props defeating memoisation: React DevTools Profiler shows why each component rendered); effects running twice in development (Strict Mode, deliberately, to expose missing cleanups); stale closures in effects and callbacks; waterfalls of data fetching inside nested components; hydration mismatches in server-rendered apps (server and client rendered different markup: often dates, random ids, or locale).

Angular at L3: change detection

Angular (relevant to many enterprise Java shops) traditionally used zone.js, which monkey-patches browser async APIs (events, timers, XHR, promises) so Angular knows something may have changed and runs change detection: walking the component tree and comparing template-bound values to their previous values, updating the DOM where they differ. ChangeDetectionStrategy.OnPush limits checking to components whose inputs changed by reference (or that emitted events or used the async pipe), which is the main L4 performance lever. Signals (stable since Angular 17, with zoneless change detection the default for new applications since Angular 21, November 2025) invert the model: reactive values that know their dependants, so Angular updates exactly what depends on a changed signal without zone.js or tree walking. L4 signatures: ExpressionChangedAfterItHasBeenCheckedError (a binding changed during the check, usually from a lifecycle hook mutating state), slow change detection from expensive template expressions or huge *ngFor/@for lists without track, memory leaks from un-unsubscribed RxJS subscriptions (use takeUntilDestroyed or the async pipe).

Search from first principles

A search engine is built around an inverted index: for each term, the list of documents containing it (a postings list, with term frequencies and positions). A query looks up its terms' postings and scores the documents. BM25, the default scoring in Lucene (Elasticsearch, OpenSearch, Solr), rewards terms that are rare in the corpus (IDF), with diminishing returns for repeated terms (TF saturation, k1) and a penalty for long documents (length normalisation, b):

Python
# Search from first principles: an inverted index with BM25 scoring, checked against rank_bm25
tok = lambda s: re.findall(r"[a-z]+", s.lower())
index = defaultdict(dict)                     # term -> {doc_id: term frequency}
lengths = {}
for d, text in docs.items():
    terms = tok(text); lengths[d] = len(terms)
    for t, tf in Counter(terms).items(): index[t][d] = tf
N, avgdl = len(docs), sum(lengths.values()) / len(docs)

def bm25(query, k1=1.5, b=0.75):
    scores = Counter()
    for t in tok(query):
        postings = index.get(t, {})
        idf = math.log((N - len(postings) + 0.5) / (len(postings) + 0.5) + 1)   # rare terms weigh more
        for d, tf in postings.items():
            scores[d] += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * lengths[d] / avgdl))  # saturating tf, length-normalised
    return scores.most_common()
Text
postings for 'biryani': {2: 2, 3: 1, 5: 1}
ours      : [(2, 1.483), (5, 1.323), (3, 0.565)]
rank_bm25 : [(2, 0.583), (5, 0.518), (3, 0.228)]
query 'biriyani' (misspelt): [] → exact-term matching misses it; needs fuzzy/n-gram analysis

The same ranking as the rank_bm25 library; absolute scores differ because that library's Okapi variant computes IDF without Lucene's + 1 (which keeps IDF positive for very common terms). Scores are only meaningful within one query.

L3 beyond scoring: analysis (tokenisation, lowercasing, stemming, synonyms, n-grams; the same analyzer must apply at index and query time, or matches silently fail); index structure (immutable segments merged in the background; near-real-time refresh makes new documents searchable after about a second, not instantly); sharding and replicas; relevance tuning (field boosts, phrase matching, function scores for recency or popularity); hybrid search (BM25 plus vector similarity, fused with reciprocal rank fusion: Volume 14).

L4 problems: "my document doesn't match" (_analyze API to see the actual tokens; mapping mismatches such as a keyword field searched with full text), the misspelling above (fuzzy queries, n-gram analyzers, or spelling suggestions), relevance complaints (the explain API shows the score breakdown), slow queries (leading wildcards, deep pagination with from/size: use search_after), cluster red/yellow states (unassigned shards), mapping explosions from dynamic fields, reindexing without downtime via aliases (Volume 16).

NoSQL at L3/L4

Family Examples Data model Strengths The modelling rule
Key-value Redis/Valkey, DynamoDB (also document), etcd Key → value Simple, fast, predictable Design keys for your access patterns
Document MongoDB, Couchbase, Firestore JSON-like documents Flexible schema, nested aggregates Embed what's read together; reference what's shared or unbounded
Wide-column Cassandra, ScyllaDB, Bigtable, HBase Partition key → sorted rows Massive write throughput, linear scale One table per query; partition key spreads load, clustering key orders within
Graph Neo4j, Neptune Nodes and edges Multi-hop relationship queries Model relationships as first-class edges
Time-series InfluxDB, Prometheus TSDB, TimescaleDB Series of timestamped points Compression, downsampling Bound cardinality

The defining L3 difference from relational design: model for the queries, not the entities. In DynamoDB or Cassandra you list access patterns first and design keys (often a single table with composite keys) so each pattern is a single-partition lookup; joins and ad-hoc queries are expensive or impossible. In exchange you get predictable latency at any scale.

Partitioning spreads keys across nodes. Naive hash(key) mod N remaps almost every key when N changes; consistent hashing (a hash ring with virtual nodes, used by Dynamo, Cassandra, Riak and many caches) moves only the keys the new node takes over:

Python
# Partitioning keys across nodes: hash mod N vs consistent hashing with virtual nodes, when a 5th node joins
def mod_n(nodes):  return {k: nodes[h(k) % len(nodes)] for k in keys}

def ring(nodes, vnodes=100):
    points = sorted((h(f"{n}#{v}"), n) for n in nodes for v in range(vnodes))
    hashes = [p for p, _ in points]
    return {k: points[bisect.bisect(hashes, h(k)) % len(points)][1] for k in keys}
Text
hash mod N                             keys moved when adding n5: 80.2%   per-node keys after: [19642, 20033, 20033, 20110, 20182]
consistent hashing (100 vnodes/node)   keys moved when adding n5: 21.8%   per-node keys after: [16587, 17997, 21544, 21843, 22029]
ideal: 1/5 = 20.0% of keys move (only those the new node takes over)

Close to the ideal 20% instead of 80% (for a cache, the difference between a brief dip in hit rate and a near-total flush that stampedes the database). The trade-off is visible too: mod-N spreads keys almost perfectly evenly; the ring with 100 virtual nodes per node is within about ±15%, and more virtual nodes tighten it. (Rendezvous hashing and jump consistent hash are alternatives with other trade-offs.)

L4 signatures: hot partitions (one key or partition taking disproportionate traffic: a celebrity user, a date-based key where today gets all writes; DynamoDB throttles that partition even with spare table capacity; fix with write sharding/suffixes or better keys), large partitions in Cassandra (unbounded clustering rows per partition: bucket by time), tombstone build-up from deletes slowing reads, read-after-write surprises from eventual consistency (DynamoDB's default reads are eventually consistent; strongly consistent reads cost double), MongoDB queries without supporting indexes (explain() showing COLLSCAN).

GPU and ML internals, for a backend engineer

You'll increasingly operate systems that serve models. L3 means knowing why they behave as they do.

Compute-bound vs memory-bound. Every operation has an arithmetic intensity: FLOPs performed per byte moved from memory. Hardware has a peak compute rate and a peak memory bandwidth; their ratio (the ridge point of the roofline model) decides which limit an operation hits. Measured on this sandbox's CPU with PyTorch:

Python
# Compute-bound vs memory-bound: arithmetic intensity (FLOPs per byte moved) decides which limit you hit
rows = {
    "elementwise x + y (64M floats)": bench(lambda: torch.add(x, y, out=z), 64 * 2**20, 3 * 4 * 64 * 2**20),
    "matmul 2048 x 2048":             bench(lambda: a @ b, 2 * n**3, 3 * 4 * n * n),
}
Text
elementwise x + y (64M floats)        1.6 GFLOP/s    19.5 GB/s  intensity    0.08 FLOP/byte
matmul 2048 x 2048                  188.1 GFLOP/s     0.6 GB/s  intensity  341.33 FLOP/byte

The element-wise add does one FLOP per 12 bytes moved: it runs at memory bandwidth and achieves under 1% of the compute rate. The matrix multiply reuses each loaded value hundreds of times and runs at compute speed. GPUs have far more compute than bandwidth (an H100 does on the order of 1,000 dense bf16 TFLOP/s against about 3.35 TB/s of HBM bandwidth: a ridge point near 300 FLOP/byte), so anything with low intensity leaves most of the chip idle. This is why ML engineers fuse kernels (FlashAttention fuses attention's steps to avoid writing intermediate matrices to memory) and why batching matters.

Why LLM serving is memory-bound. Generating each token reads all the model's weights (and the KV cache) from memory to do a small amount of computation per sequence. Batching many sequences together reuses each weight load across the batch, raising intensity. The KV cache (keys and values of every previous token, every layer) is the other memory consumer:

Python
# Why LLM serving is memory-bound: KV-cache size per token and per request (a Llama-3-8B-like shape)
layers, kv_heads, head_dim, bytes_per = 32, 8, 128, 2            # GQA with 8 KV heads; fp16/bf16
per_token = 2 * layers * kv_heads * head_dim * bytes_per          # K and V, every layer
Text
KV cache per token: 128 KiB
  context   2,048 tokens →   0.25 GiB per sequence
  context   8,192 tokens →   1.00 GiB per sequence
  context  32,768 tokens →   4.00 GiB per sequence
  context 131,072 tokens →  16.00 GiB per sequence
weights ≈ 14.9 GiB in bf16; an 80 GiB GPU leaves ≈ 65 GiB for KV cache → ≈ 65 concurrent 8k-token sequences

Long contexts eat GPU memory, which limits concurrent requests and therefore throughput and cost. Serving engines respond with paged attention (vLLM: KV cache in fixed-size blocks, like virtual memory, eliminating fragmentation), continuous batching (adding new requests to the running batch between steps rather than waiting for a batch to finish), prefix caching (reusing the KV cache of shared prompt prefixes), quantisation (int8/fp8/int4 weights and KV cache: less memory and bandwidth, small quality cost), and speculative decoding (a small model drafts tokens that the large model verifies in parallel).

What L3/L4 lets you do as a backend engineer: read a serving dashboard (time to first token, inter-token latency, tokens/s, batch size, KV-cache utilisation, queue depth) and say whether the problem is prefill (long prompts), decode (memory bandwidth), or queueing (capacity); autoscale on queue depth and KV utilisation rather than CPU; ask the right questions of an ML team (What's the p95 prompt length? Can we cache the system prompt prefix? What does int8 do to our eval scores?); and recognise when a hosted API is cheaper than a GPU fleet (often, until steady high volume).

Lab: search three ways in PostgreSQL

Setup. PostgreSQL 16 on the lab machine; a docs table of 106,920 passages (the 5,346 chunks of this textbook's Volumes 1–14 from Volume 14b's lab, repeated 20 times), 105 MB. Queries timed as the average of 5 runs after a warm-up, all data cached in memory.

Experiment 1: speed and recall

Query Index Time Rows matched
body ILIKE '%idempotency%' none 601.6 ms 2,660
body ILIKE '%idempotency%' trigram GIN (gin_trgm_ops, 91 MB, built in 15.2 s) 23.6 ms 2,660
tsv @@ plainto_tsquery('english', 'idempotency') GIN on a stored tsvector (29 MB, built in 14.5 s) 3.2 ms 4,760
full-text 'idempotent keys' same 1.7 ms 2,540
ILIKE '%idempotent keys%' none 647.9 ms 0

to_tsvector('english', 'idempotency idempotent idempotancy keys') returns 'idempot':1,2,3 'key':4: the English stemmer reduced every form to one token and dropped the plural, which is why full-text search found 79% more passages than the substring match and matched the phrase that ILIKE missed entirely.

Experiment 2: misspellings

Query Full-text (stemmed) Trigram word_similarity (<%)
"idempotancy" 4,760 (stems to the same idempot, by luck) 2,620 in 696 ms
"idempotncy" 0 4,820 in 742 ms

Full-text search normalises words; it doesn't measure similarity, so a typo that changes the stem finds nothing. Trigram similarity tolerates typos but scanned far more of the index (hundreds of milliseconds here). Search engines (Elasticsearch, OpenSearch, Typesense, Meilisearch) combine both ideas, plus relevance tuning, synonyms and per-field analysers.

Experiment 3: ranking

ts_rank_cd over "retry with idempotency key" returned results in 9.0 ms, but the top three were the same passage three times (the corpus repeats each chunk 20×). Duplicate and near-duplicate content swamps rankings; real search pipelines deduplicate at ingestion and diversify results. It's also a reminder that relevance needs evaluation (Volume 14b, chapter 162), not just a ranking function.

When is PostgreSQL search enough?

For a product like TiffinBox (menus, help articles, a few hundred thousand documents), PostgreSQL full-text plus trigram indexes covers most needs with no extra system to run. A dedicated engine earns its operational cost with large corpora, heavy relevance tuning, faceting at scale, typo tolerance by default, or multilingual analysis.

Try it yourself

  1. Add a simple (unstemmed) tsvector and compare matches with the english one.
  2. Combine full-text and trigram: try full-text first, fall back to word_similarity when it returns nothing.
  3. Deduplicate the corpus and rerun Experiment 3; then add ts_headline snippets.
  4. Load the same documents into OpenSearch (or Meilisearch) and compare typo handling and latency.

Revision sheet: breadth at L3/L4

Key ideas

  • Breadth targets L3/L4: explain internals and diagnose problems that cross into the area.
  • Front end: the browser rendering pipeline, the event loop, network waterfalls, Core Web Vitals.
  • React: reconciliation, keys, re-render causes, memoisation; Angular: zones and change detection, signals, OnPush.
  • Search: analysis (tokenise, normalise, stem), inverted indexes, BM25 ranking, n-grams for fuzzy matching, relevance evaluation.
  • NoSQL: document, key-value, wide-column, graph; model by access pattern; consistency and partitioning trade-offs.
  • GPU/ML: SIMT execution, memory hierarchy and bandwidth, batching, mixed precision, why inference is memory-bound.

Numbers to remember

  • Lab: ILIKE substring scan 602 ms vs trigram index 24 ms vs full-text GIN 3.2 ms on 106,920 passages.
  • Lab: full-text matched 79% more passages (stemming) but found nothing for "idempotncy"; trigram found 4,820.

Pitfalls

  • LIKE '%…%' search in production on large tables.
  • Assuming full-text search handles typos.
  • Blaming "the front end" or "the database" without tracing the request.
  • Choosing NoSQL for flexibility without knowing the access patterns.
  • Treating GPUs as faster CPUs without considering memory bandwidth and batching.

Glossary

  • Stemming: reducing words to a common root.
  • Trigram: a 3-character substring used for fuzzy matching.
  • Reconciliation: React's process of computing UI updates.
  • Change detection: Angular's process of updating views when data changes.
  • SIMT: single instruction, multiple threads, the GPU execution model.