Index of every page on this site: llms.txt
All skills
teamdable avatar

/nodejs-hot-path-perf

@eb28d37
Run it yourself

Structurally locate the per-request hot path of an HTTP Node.js server, then find and remove the allocations that escape on that path (objects V8's escape analysis cannot eliminate, so they land on the heap and create GC pressure). Targets servers that fan out to N items per request (search/ranking APIs, ad servers, API gateways), where a single escaping allocation is multiplied by the request rate. Use when the user asks about "node server performance", "request hot path", "escape analysis", "reduce allocations", "GC pressure", "find perf wins", "run this on my server", "where is it slow", or "flamegraph".

  • 7 files
  • 58.9 KB
  • Updated 3 months ago
  • GitHub
Use this Skill: https://skilld.dev/gh/teamdable/nodejs-hot-path-perf/nodejs-hot-path-perf

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

SKILL.md

≈159 tokens for metadata: the name and description. ≈3.8k when used: this file. ≈9k more on demand in 4 files.

How this Skill uses context

Before choosing a Skill, your Agent reads its name and description. All available Skills share that space.

This Skill turns off automatic use in Claude Code. Its description stays out of the automatic Skill list by default.

Example settings and source

The example uses a 200k-token context and default Claude Code settings. The count includes the name, description, separators, and when_to_use when present. Codex also counts local file paths.

Skit's source and limits: Codex 0.160.1, Claude Code 2.1.292.

Node.js Request Hot-Path Escape Analysis

A method for HTTP Node.js servers: (1) structurally locate the per-request hot path → (2) find the allocations that escape on that path via escape analysis → (3) eliminate or amortize them.

Patterns are priors, not conclusions. P1/P2/P3 in references/patterns.md are hypotheses that narrow down where to look. A candidate is confirmed not by shape-matching but by applying V8 escape analysis case by case: "does this object leave its allocating function, and is that multiplied by the request rate?" Do not build a candidate list by grepping for shapes.

The three worked examples come from a production Node.js service. P3 is elimination of escaping tuples/arrays (pure alloc win), P1 amortizes an escaping transform to once per reference (alloc win). P2 is strictly CPU-dominant — it avoids a dayjs().format() call via a time bucket, where 936 ns of the 1198 ns per call is format CPU and the alloc saving is a side effect. Escape analysis points directly at P3 and P1; expensive calls like P2 surface through CPU cost as well (all three converge on amortize/eliminate).

Background: V8 escape analysis & scalar replacement

V8's optimizing compiler (TurboFan) removes a heap allocation when it can prove the object allocated inside a function does not escape that function — scalar replacement puts the fields in registers/stack, at zero GC cost.

An object escapes (allocation cannot be removed, it goes on the heap) when it is:

  • returned from the function.
  • stored somewhere heap-reachable (a field of another object/array, a global, this, an external collection).
  • passed to a call that is not inlined — the callee could capture it, so V8 conservatively treats it as escaping. This includes megamorphic call sites and large/unoptimized callees.
  • captured by a closure that itself escapes.
  • allocated inside a function that is never optimized or gets deoptimized — escape analysis never runs on it.

One escaping allocation on a per-request hot path = N heap allocations per request = young-gen GC churn plus allocation CPU, multiplied by the request rate. That is what we are hunting.

When to use this

  • Finding CPU/latency/GC wins in an HTTP request-serving Node.js server.
  • Code that iterates a per-request collection (candidates, products, documents, ads) and builds an object per item.
  • "Run this on my server too" — applying the method (hot path → escape analysis) to a new repository.

When not to use it: algorithmic complexity (O(n²)→O(n)), I/O-bound work (waiting on DB/network), batch/cron jobs. This skill is only for CPU/alloc-bound request paths.

Explore code with a call-graph tool (LSP call hierarchy, a code-graph MCP server, IDE "find callers") rather than grep. Escape analysis is reading and reasoning about code, not scanning it for patterns.


Phase 1 — Structurally locate the request hot path

Find it by reading the call graph from the HTTP entry point down to the per-request fan-out. Not by grepping.

  1. HTTP entry point: route registration → middleware chain → handler. In Express: router → app.use / router.post → controller.
  2. Fan-out point: inside the handler, where a collection whose length is proportional to request input is iterated (for / .map / .forEach over candidates, products, documents). Code that runs once per request is not the hot path — only the inside of the N (or N×K, N×M) loop is.
  3. Tools: trace entry point → leaf in one call if your tooling supports it (including dynamic hops). Use caller lookup to gauge call frequency, and read the loop bodies directly.

Output: a hot-path map shaped like "route X → middleware Y → handler Z, calls f/g/h inside a loop over N=candidate count per request".

Phase 2 — Argue hotness from code (no profiling, no server startup)

Do not boot the server locally or profile it. Config, secrets, DB, and cache setup cost far more than they are worth. Argue hotness from the fan-out structure, by reading code alone. The first production PR behind this skill did exactly that: no prod profiling, structural hotness argument plus an isolated benchmark as proof.

Count calls per request from the fan-out found in Phase 1: N (candidates) × K (sub-items) × M (filters). Example: if enrichCandidate runs for N=200 candidates × K=50 variants, that is ~10,000 conversions per request. That product is the hotness verdict — fan-out depth is the amplification factor. Code that runs once per request is not hot.

Optional (only for fleet-impact conversion, not required): remote production metrics (your metrics warehouse, Prometheus, Datadog) for actual calls/sec and peak. Zero local setup, remote queries only. One of the production PRs used this to convert a saving into fleet CPU-hours. But it is unnecessary for the hotness verdict — the structural argument is enough. Full-server flamegraphs and heap profiles are not used in this skill.

count ≠ cost. N×K×M is a call count, not per-call cost — a 10,000-iteration loop might be 0.5% of the request, while a single JSON.parse is 40%. The structural argument is a proxy for hotness. To confirm, flamegraph the isolated harness from Phase 4 (0x / node --prof) and look at the time distribution inside the path — cheap, and still no full server. On a repository you are seeing for the first time, do this one profile to locate the hot path before switching to structural arguments. On a server whose hot path is already known, start from the structural argument.

Output: "~M calls per request" per hot function, from structure. Per-call cost and allocation evidence come from the Phase 4 isolated benchmark.

Phase 3 — Escape analysis: does each allocation escape, and can it go away?

Read the hot functions that Phases 1–2 pointed at, and reason about each allocation inside them. Mechanism reasoning, not pattern matching. (No profiler — escape is decided by reading code, not by measuring.)

For each allocation (object/array/tuple literal, spread, .map() / fromEntries result, per-call closure):

  1. Does it escape? — Is it returned? Stored into another object/array/collection? Passed to a call that will not be inlined (library function, megamorphic site, large callee)? Captured by an escaping closure? Any single yes means V8 cannot remove it → it goes on the heap.
  2. Is the escape multiplied by request rate? — Is it inside the N loop from Phase 1? If yes, that is N heap allocations per request.
  3. Pick one of two prescriptions:
    • (a) eliminate — remove the escape so V8 can scalar-replace, or remove the allocation entirely. Example: inline the control flow instead of building an intermediate array to iterate ([fn, args].some(...) → an || chain). Unbox an object literal into primitives instead of passing it across a call boundary.
    • (b) amortize — when the escape is essential (the value genuinely must be returned or stored), stop building it on every call and build it once and cache it. Example: memoize the transform once per reference in a WeakMap (P1), or cache the expensive call itself along its slow-changing dimension so the hot path never allocates (P2).

If it does not escape, leave it alone — but remember static reasoning is a prediction, not a verdict. A non-escaping local allocation is scalar-replaced in the optimized tier and costs nothing (unoptimized Ignition/Sparkplug code still allocates on the heap). Escape reasoning is best-effort and can be wrong (the function never tiers up, escape analysis bails on a loop or phi node). Use static reasoning to narrow candidates, but confirm by measurement before discarding or committing — --trace-gc, or --trace-opt / --trace-deopt / %GetOptimizationStatus. Measurement is the authority. Only allocations that satisfy both escape and request-rate amplification are candidates. Do not force things into categories. Never ask "is this a P1, P2, or P3?" — ask only "does this escape, and can it go away?" Prescription code samples live in references/patterns.md (a casebook of escaping-allocation removals; read it right before applying a fix).


Phase 4~8 — Proving and shipping (supporting machinery)

Phase 4 — Isolated logic benchmark (no server startup)

Do not run the real server. Copy just the logic of the hot function into a standalone .mjs with no I/O, DB, cache, or config, and compare before/after. This is exactly how the first production PR was proven: the core of the enrichment middleware was isolated and measured with process.hrtime.bigint() across N and K scenarios. Template: scripts/bench.mjs.

  • CPU: stabilize with --expose-gc → warm up → process.hrtime.bigint(), median over several batches. Use realistic shapes (N, K, unique %) and several scenarios (worst case, early exit).
  • Watch out for DCE: the benchmark must consume the return value of fn() through a sink (blackhole in bench.mjs). Without it the allocations under measurement get dead-code eliminated and µs and B/call come out falsely low.
  • Match the engine: the target is a Node server, so measure with Node (--trace-gc "scavenge" is V8-specific). Do not use Bun — JSC has different escape analysis and GC, so the numbers do not transfer.
  • Allocation/escape evidence (without a full-server heap profile): run node --expose-gc --trace-gc bench.mjs and compare minor GC (scavenge) counts before and after — if the elimination removed escaping allocations, scavenges go down. (Or use the process.memoryUsage().heapUsed delta.)
  • Verifying the escape prediction (optional, V8 introspection): node --trace-opt --trace-deopt shows whether the hot function optimized or deoptimized, --allow-natives-syntax + %GetOptimizationStatus(fn) reports its optimization state, and --trace-turbo exposes escape analysis results — ask the engine directly whether your static prediction was right.

Phase 5 — Apply the prescription

Apply eliminate/amortize per references/patterns.md. One change = one PR.

Before amortizing, sweep the whole request path for other places computing the same value. A hot loop is what catches your eye, so that is where you fix it — but a sibling call doing the same transform on the same input often survives further down the pipeline. (In one production case, a loop's 2N calls were reduced to 1, while a post-processing stage two steps later was still compressing the same input a second time.) Fixing only the loop overstates the saving and leaves the remaining site for the next person to rediscover.

Phase 6 — Safety verification

  • Block mutation when amortizing (cached/shared values): a shared or frozen object must be read-only at every call site. Verify the returned value never sees obj.field =, .push(, or Object.assign(obj, ...), and add Object.freeze.
  • Worker scope: a module-level cache is independent per cluster worker — fine as long as the value is derived and idempotent.
  • Behavioral equivalence: after elimination, observable semantics (metric counts, call order, side effects) must be preserved. || short-circuits identically to .some().

Phase 7 — Gating tests

Make the test's coverage match what its name and comments claim. To lock in "K calls per request", one test has to exercise every stage that computes that value. Calling a single module while claiming a property of the whole request leaves the remaining computation outside the test's field of view, and later someone reads that test and concludes the optimization is finished. If you scope the test narrowly, scope the name and comments narrowly too.

Lock the invariant the optimization depends on. Amortize: same input → same reference (toBe) and the cache computed once; input replaced → recomputed. Eliminate (chain): calls happen in declaration order, nothing runs after the first true (short-circuit), and a throwing implementation in a later slot does not throw (proving laziness). Import constants from the source, and follow the repo's test conventions. Details in references/patterns.md.

Phase 8 — Report

Use references/report-template.md: TL;DR (per-request + fleet) → Changes → Why (call sites + N conversion + production data) → per-call/alloc cost breakdown → Risk → Tests. No savings claim without a measurement.


Applying this to a new repository

When asked "run this on my server":

  1. Map the request hot path structurally (Phase 1) — route → fan-out via the call graph. No grep.
  2. Argue hotness from structure (Phase 2) — calls per request from the fan-out product (N×K×M). But count ≠ cost: on an unfamiliar repository, confirm the hot path's location with one profile (flamegraph of the isolated harness, or --prof in staging) before switching to structural arguments. On a server whose hot path is already known, start structural. No full-server startup. Production metrics are optional, for fleet conversion.
  3. Read the hot functions and run escape analysis (Phase 3) — does each allocation escape, is it multiplied by request rate, can it be eliminated or amortized? Reading only. Not pattern matching.
  4. Isolate the logic and benchmark it (Phase 4) to prove the win → apply eliminate/amortize, test, and report (Phases 5–8). One change = one PR.
  5. Report: hot-path map + structural argument (calls per request) + isolated benchmark evidence (µs, GC counts) + per candidate "where it escapes, the prescription, estimated impact". Confirm before applying.

Expectation: most fan-out HTTP servers have at least one escaping allocation multiplied by the request rate. But do not assume what shape it will take — following escapes through the code turns up things outside this catalog.

Core principles

  • Patterns are priors; escape analysis decides. P1/P2/P3 only narrow down where to look — never confirm a candidate by shape. Apply the escape-analysis mechanism case by case.
  • The request hot path is the anchor. Ignore any allocation that is not multiplied by N per request. Only escape × request-rate qualifies.
  • If it does not escape, do not touch it. Local allocations that V8 scalar-replaces in the optimized tier cost nothing (though a static verdict is a prediction — measure when unsure).
  • Reason from code without booting the server; isolate the logic to benchmark. Full-server profiling is skipped (setup cost), but an unfamiliar repository can afford one flamegraph of the isolated harness to locate the hot path. Argue hotness from fan-out structure and prove it with an isolated benchmark (µs plus --trace-gc scavenge counts, on the same engine as production). Static escape verdicts are predictions — when unsure, check with --trace-opt / %GetOptimizationStatus. A savings claim without a benchmark is not a reason to merge.
  • Eliminate first, amortize only if you cannot. Amortizing introduces shared-mutation risk → freeze and verify read-only usage.
  • One change = one PR.

MIT License · Copyright (c) 2026 Dable Inc. · See LICENSE.

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No third-party reports yet.

Signed by skilld at eb28d37. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 3 months ago
disable-model-invocation
true

README badge

README badge for teamdable/nodejs-hot-path-perf