
Profiling ESLint Before a napi-rs Rewrite: Finding Hotspots That Matter
The report that ESLint's creator rejected a full Rust rewrite while experimenting with napi-rs modules is worth reading as a signal about direction, not as a performance result. The supplied source is a headline and a one-line summary: no primary statement, no implementation details, no affected versions, no benchmarks. As secondary reporting, it does suggest a more useful engineering question than "rewrite or don't rewrite" — namely, which specific function inside the linting pipeline deserves to cross a native boundary.
This post answers that question with a profile you can defend. You will measure ESLint's real pipeline — parsing, scope analysis, rule traversal, plugin dispatch, and fix passes — then use the numbers to decide whether a napi-rs kernel earns its Rust maintenance and distribution cost, or whether the JavaScript itself is what should be fixed first.
Measurement convention used throughout. Every number I want you to trust is either arithmetic (Amdahl's law) or a labelled output shape. Values inside <> are placeholders for your run. Blocks captioned "shape" show the structure your tool emits with the values replaced. I did not run ESLint on your repository, and nothing below should be read as a benchmark result.
On this page
The napi-rs Report Is a Reason to Profile, Not a Performance Result
What the supplied report claims: ESLint's creator rejected a full Rust rewrite while experimenting with napi-rs modules
The item, dated 2026-12-05 and published by MLQ.ai, says ESLint's creator rejected a full Rust rewrite while testing modules built with napi-rs. That sentence contains two separable claims:
- A decision — no full rewrite.
- An activity — napi-rs modules are being tried out.
Only the first has an engineering consequence you can act on, and even that is a report about someone else's project. The second is a hint about an incremental path: keep the JavaScript linter, move something narrow into Rust.
This is secondary reporting. There is no linked commit, RFC, issue thread, or benchmark in the supplied material. Treat "ESLint is adopting native modules" as unverified, and do not repeat it as fact in a design doc.
What remains unverified: the December 5, 2026 item supplies no primary statement, implementation details, affected versions, or benchmarks
Specifically, the source does not include:
- A primary statement. No link to a blog post, talk, or repository change from anyone working on ESLint.
- Implementation detail. Nothing says which subsystem was prototyped — parser, scope analysis, rule dispatch, config resolution, or something outside the core.
- Version information. Which ESLint major, which napi-rs major, which Node-API level. Unknown.
- Numbers. Not one timing, not one corpus description, not one statement of what was measured.
That gap matters because the same ambiguity shows up in almost every "we moved X to Rust" story I read. A 30% win on a synthetic microbenchmark and a 30% win on eslint src in a real repository are unrelated claims. Only the second one changes developer experience.
Technical position: preserve JavaScript plugin compatibility and move only measured, sufficiently coarse-grained hotspots across the native boundary
Here is my position, stated up front so you can argue with it:
The plugin API is the product. ESLint's value is the tens of thousands of rules, parsers, processors, and formatters written against context.report(), visitors, SourceCode, and fixers. Any native work that changes observable behaviour there is a net loss regardless of throughput. A rewrite that is 3× faster and breaks @typescript-eslint is a rewrite nobody installs.
Native code is justified per-kernel, not per-project. A function qualifies only if it holds a meaningful share of end-to-end wall time, operates on coarse-grained data, and is pure enough that it never needs to call back into JavaScript per AST node.
The default answer is "optimize the JavaScript". Most slow lint runs I have looked at are slow because of type-aware program construction, redundant rule configuration, cache misses, or repeated work in fix passes — not because V8 is bad at property access.
And the ceiling is low. If the native candidate is 20% of runtime, even infinite acceleration caps you at 1.25×. That number, not a Rust benchmark, is what should decide the project.
Map the ESLint Linting Pipeline Before Measuring It
Follow a file through discovery, configuration resolution, reading, parsing, scope analysis, traversal, rule listeners, fixes, and formatting
A single file passes through roughly eight stages, and their cost profiles vary wildly:
| Stage | Where it roughly lives | TIMING=1 | --stats | CPU profile |
|---|---|---|---|---|
| Discovery, globbing, ignore matching | CLI engine / file enumerator | no | no | inclusive only |
| Config resolution per file | config loader (flat config) | no | no | inclusive only |
| Read + parse | fs + espree (or plugin parser) | no | parse.total | yes, clearly |
| Scope analysis | eslint-scope | no | not broken out | yes |
| Traversal + rule listeners | Linter + node event generator | per-rule | rules.*.total | yes |
| Fix passes (re-lint) | verifyAndFix loop, up to 10 passes | partial | fixPasses | yes |
| Formatting | formatter, once at end | no | no | yes |
Two structural facts drive everything else:
Parsing produces more than an AST. Espree returns an ESTree AST plus tokens, comments, and location/range data, and SourceCode wraps all of it. Rules read tokens and comments directly, so a native parser that returns only an AST is not a drop-in replacement — it breaks the token-based rules that make ESLint useful.
Fix passes are re-lints. When fixes apply, ESLint re-runs verification on the fixed text, up to a small fixed number of passes. A file that takes three passes costs roughly three parses and three traversals. If your profile shows high total time on a fix-heavy corpus, the win may be in fewer passes, not faster passes.
Explain parser and plugin extension points, including why traversal and rule callbacks are interleaved rather than independent timing buckets
This is where most profiling intuition breaks.
The linter does not "traverse the tree, then run the rules." It traverses once and, at each node, dispatches to every rule listener registered for that node type or selector. Traversal is the loop; rule bodies are the loop body. There is no clean boundary you can time independently, because traversal cost and rule cost are the same call stack interleaved millions of times.
Consequences:
TIMING=1can attribute time to a rule, but the traversal machinery it runs inside has no line item. Any "unaccounted" time is probably traversal, dispatch, scope lookups, or the timer's own overhead.- A high self time on dispatch functions proves dispatch exists, not that it is expensive. You need a controlled experiment (later section) before drawing that conclusion.
- Custom parsers and processors sit at well-defined edges and are easy to measure in isolation; rules are not.
Distinguish end-to-end CLI latency, per-file linting time, CPU consumption, and editor responsiveness
Four different numbers, four different decisions:
| Metric | What it answers | How it misleads |
|---|---|---|
| CLI wall clock | "Is CI slow?" | dominated by startup, config load, and I/O for small repos |
| Per-file lint time | "Which files are pathological?" | hides fixed per-run costs entirely |
| CPU time / CPU-seconds | "What does this cost in CI dollars?" | ignores waiting and threadpool contention |
| Editor responsiveness | "Is the developer blocked?" | depends on incremental/partial linting, not full runs |
A native kernel optimised against CLI wall clock on a 12-file project will look like a regression, because startup dominates and the kernel never runs long enough to matter. Decide which of these four you are optimising before you measure, and write it down.
Build a Reproducible Baseline on a Representative Repository
Record Node.js, ESLint, parser, plugin, operating-system, CPU, and lockfile versions with reproducible commands
A timing without conditions is not a result. Capture all of it into a file you commit next to the benchmark script:
{
node -v
node -p "process.versions.napi"
npx eslint --version
npm ls eslint espree @typescript-eslint/parser @typescript-eslint/eslint-plugin --depth=0
uname -srm
node -p "require('node:os').cpus()[0].model"
sha256sum package-lock.json | cut -c1-16
} | tee bench/environment.txt
Shape of that output:
v<node-major>.<minor>.<patch>
<node-api-version>
v<eslint-major>.<minor>.<patch>
<package tree with resolved versions>
<kernel-name> <kernel-release> <machine>
<exact CPU model string>
<first 16 hex chars of the lockfile hash>
The lockfile hash is the part people skip. Rule and plugin versions change performance far more than ESLint's own version does, and "we upgraded something" is not a reproducible claim.
Select a fixed corpus covering production JavaScript, TypeScript when applicable, large files, and rule-heavy files without inventing a representative workload
Two honest ways to get a corpus:
- Your own repository at a pinned commit. Best signal, worst external validity.
- A public repository you pin by commit SHA. Better for sharing, still not "representative of JavaScript" in any statistical sense.
Do not claim representativeness. Claim a fixed corpus with named characteristics:
- production JavaScript, linted with the config the project actually ships;
- TypeScript with type-aware rules if the project enables them — because that path pays for a TypeScript program build, which is a different cost regime entirely;
- at least two files above ~2,000 lines, since rules with quadratic behaviour only show up there;
- at least one file with many diagnostics, since reporting and formatting cost scales with message count.
Record the per-file line counts so the "slow files" table later is interpretable.
Separate uncached runs, ESLint cache-hit runs, process startup, and filesystem-cache effects; keep concurrency and autofix settings explicit
Four runs, not one:
## 1. cold-ish: no ESLint cache
npx eslint src --no-cache
## 2. cache miss then hit
rm -f .eslintcache && npx eslint src --cache
npx eslint src --cache
## 3. process startup floor: config resolution and nothing else
npx eslint --print-config src/index.js > /dev/null
## 4. fix pass cost without touching files
npx eslint src --no-cache --fix-dry-run
Notes that matter:
--fix-dry-runruns the fix loop without writing, so you can price fix passes without mutating the working tree. Comparing it to a plain run gives you the cost of the extra passes.- Concurrency: recent ESLint versions accept
--concurrency, but it is new enough that you must check your install (npx eslint --help) rather than assume. If you use it, record the value, and note that the runner is then measuring multiple worker threads, not one. - Filesystem cache is warm in any developer machine benchmark and cold on a fresh CI runner. If you care about CI, warm cache is the wrong default; say which one you measured.
- Startup floor (run 3) is the number that kills small-repo optimisations. If startup is 600 ms and full lint is 700 ms, there is almost nothing left to accelerate.
Define repeated-run methodology and a results table containing corpus size, configuration, median latency, spread, and diagnostic counts
Use sequential runs with warmups, on an otherwise idle machine, and report spread rather than a single number:
// Sequential CLI runs. Report median and spread, never a single timing.
const runs = Number(process.env.RUNS ?? 10);
const args = ["./node_modules/eslint/bin/eslint.js", ...process.argv.slice(2)];
const times = [];
for (let i = 0; i < runs; i++) {
const t0 = performance.now();
const r = spawnSync(process.execPath, args, { stdio: "ignore" });
const dt = performance.now() - t0;
// ESLint exits 1 when lint problems are found. That is not a failure.
if (r.status !== 0 && r.status !== 1) throw new Error("eslint exited " + r.status);
times.push(dt);
}
times.sort((a, b) => a - b);
const pick = (p) => times[Math.min(times.length - 1, Math.floor(p * times.length))];
console.log("args ", args.slice(2).join(" ") || "(none)");
console.log("runs ", runs);
console.log("median ms ", pick(0.5).toFixed(0));
console.log("p05 ms ", pick(0.05).toFixed(0));
console.log("p95 ms ", pick(0.95).toFixed(0));RUNS=10 node bench/run.mjs src --no-cache
The results table you fill in:
| Corpus | Files | Config | Median (ms) | p05–p95 | Diagnostics |
|---|---|---|---|---|---|
<repo-a @ sha> | <n> | flat config, <k> rules, <type-aware?> | <...> | <...> | <...> |
<repo-b @ sha> | <n> | <...> | <...> | <...> | <...> |
If p95 is more than ~20% above p05 on an idle machine, fix the environment before profiling. A noisy baseline cannot support a 10% optimisation claim, and a native rewrite is usually a 10% claim.
Collect ESLint Timing Data Before Opening a CPU Profile
Run TIMING=1 with the locally installed ESLint CLI and explain what aggregate rule timing does and does not measure
TIMING=1 npx eslint src --no-cache
Shape of the output (values replaced):
Rule | Time (ms) | Relative
:-----------------------------------------|----------:|--------:
<plugin-a>/<rule-1> | <value> | <pct>%
<plugin-b>/<rule-2> | <value> | <pct>%
<plugin-b>/<rule-3> | <value> | <pct>%
What it measures: clock deltas around each rule's listener invocations, aggregated per rule across all files. What it does not measure:
- parsing, scope analysis, config resolution, file I/O, formatter output;
- traversal and dispatch cost outside any rule body;
- TypeScript program construction, which type-aware rules trigger implicitly and which often dwarfs the rule bodies themselves;
- its own overhead.
TIMING=1adds two clock reads per listener call. With millions of calls that is measurable, so use the table for ranking, never as an absolute budget.
Use --stats with JSON output on an ESLint version that supports it; retain per-file and per-pass data rather than flattening fix passes
--stats gives you per-file, per-pass data instead of one aggregate:
npx eslint src --no-cache --stats -f json > /tmp/eslint-stats.json
Check that your version supports it, and inspect the shape before writing any summariser against it:
npx eslint --help | grep -c -- --stats
node -e "const r=require('/tmp/eslint-stats.json');console.log(Object.keys(r[0]));console.log(JSON.stringify(r[0].stats,null,2).slice(0,600))"
Shape (verify against your version — field names have changed as the feature matured):
{
"fixPasses": 1,
"times": {
"passes": [
{
"parse": { "total": 4.2 },
"rules": { "no-unused-vars": { "total": 1.8 } }
}
]
}
}
The important field is passes. Flattening it hides exactly the thing you are looking for: a file that re-parsed four times because fixes kept changing the text.
Build a small JavaScript summarizer for parse time, rule time, slow files, and repeated passes using the installed version's documented statistics shape
// Summarise --stats JSON. Run: node tools/eslint-stats.mjs /tmp/eslint-stats.json
const report = JSON.parse(readFileSync(process.argv[2], "utf8"));
const files = [];
const ruleTotals = new Map();
let totalParse = 0;
let totalRules = 0;
let multiPassFiles = 0;
for (const result of report) {
const passes = result?.stats?.times?.passes ?? [];
let parse = 0;
let rules = 0;
for (const pass of passes) {
parse += pass?.parse?.total ?? 0;
for (const [ruleId, entry] of Object.entries(pass?.rules ?? {})) {
const t = entry?.total ?? 0;
rules += t;
ruleTotals.set(ruleId, (ruleTotals.get(ruleId) ?? 0) + t);
}
}
totalParse += parse;
totalRules += rules;
if (passes.length > 1) multiPassFiles += 1;
files.push({
filePath: result.filePath,
messages: result.messages?.length ?? 0,
passes: passes.length,
fixPasses: result?.stats?.fixPasses ?? 0,
parseMs: parse,
ruleMs: rules,
});
}
const top = [...ruleTotals.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10);
console.log("files ", files.length);
console.log("parse total ms ", totalParse.toFixed(1));
console.log("rule total ms ", totalRules.toFixed(1));
console.log("files with >1 pass ", multiPassFiles);
console.log("top rules by rule ms ");
for (const [id, ms] of top) console.log(" " + id.padEnd(40) + ms.toFixed(1));
console.log("slowest files by rule ms");
for (const f of files.sort((a, b) => b.ruleMs - a.ruleMs).slice(0, 10)) {
console.log(" " + f.ruleMs.toFixed(1).padStart(9) + " passes=" + f.passes + " " + f.filePath);
}Show captured output beside the commands in the completed walkthrough; label illustrative output explicitly and do not claim unperformed measurements
Shape of the summary for a repository you run it on:
files <n>
parse total ms <value>
rule total ms <value>
files with >1 pass <value>
top rules by rule ms
<rule-id> <value>
...
slowest files by rule ms
<value> passes=<n> <path>
When you fill this in, keep parse total and rule total separate. They point at different projects: high parse time argues for a parser discussion (which, note, still has to produce tokens and comments); high rule time argues for rule configuration or a narrow kernel; a high multi-pass count argues for a fix-loop investigation, which is frequently the cheapest win available.
Use Node.js CPU Profiles to Explain Where ESLint Spends Its Time
Capture a .cpuprofile with node --cpu-prof running the local ESLint executable, then inspect it in Chrome DevTools
mkdir -p profiles
node --cpu-prof --cpu-prof-dir=./profiles --cpu-prof-name=eslint-baseline.cpuprofile \
./node_modules/eslint/bin/eslint.js src --no-cache
That writes profiles/eslint-baseline.cpuprofile. Open DevTools → Performance → load the profile file, then use three views:
- Bottom-Up, sorted by self time: which functions actually burned samples.
- Call Tree with total time enabled: the inclusive shape of a run.
- Heavy view: collapsed hot stacks, good for finding deep call chains under one rule.
Two practical notes. The default sampling interval is 1000 µs, so a 3-second run gives you ~3,000 samples — enough for a top-10, not enough for a top-200. Use --cpu-prof-interval=200 when the run is short, and profile a corpus you can run for at least ten seconds. Samples that land in native code (C++, V8 builtins, a .node addon) often appear as opaque frames, so a JS-side profile cannot price a Rust kernel; that has to be measured from the outside.
Read self time versus inclusive time and trace parser work, scope analysis, rule listeners, configuration loading, allocation, and garbage collection
| Pattern in the profile | Reading |
|---|---|
| Hot self time inside parser/tokenizer frames | parsing cost — check tokens and comments are still produced |
eslint-scope frames high inclusive | scope analysis, usually proportional to AST size |
| Wide inclusive time under linter verify with many children spread across rule IDs | rule bodies dominate |
| Self time concentrated in a dispatch/selector function | investigate dispatch with a controlled experiment, do not conclude yet |
| Config loader frames on every file | per-file config resolution not being cached as you assumed |
(garbage collector) above a few percent | allocation pressure; often an easier fix than a native kernel |
(program) / (idle) buckets | blocking native or kernel time, or waiting — not attributed to JS |
The GC line is the one I look at first. A linter allocating millions of small objects per pass will show GC prominently, and reducing allocations is a JavaScript change with a JavaScript-sized maintenance bill.
Investigate suspected plugin-dispatch overhead without assuming a callback-heavy stack proves dispatch itself is expensive
A deep stack of listener invocations looks alarming and often means very little. The right test is controlled: bind no-op rules to the same node types and measure the delta.
// bench/noop-dispatch.config.mjs — same config, plus N rules that do nothing
const N = 50;
const noopPlugin = {
rules: Object.fromEntries(
Array.from({ length: N }, (_, i) => [
"noop-" + i,
{ create: () => ({ Identifier() {}, CallExpression() {}, MemberExpression() {} }) },
]),
),
};
export default [
// your real config entries here, then:
{ files: ["**/*.js"], plugins: { noop: noopPlugin },
rules: Object.fromEntries(Array.from({ length: N }, (_, i) => ["noop/noop-" + i, "error"])) },
];
If 50 no-op rules cost a meaningful share of runtime, dispatch is genuinely expensive and worth a serious look. If they cost almost nothing, the expensive part is the bodies of your real rules, and dispatch is a distraction. Either way, you now have evidence instead of a stack trace.
Compare instrumented and uninstrumented runs, and explain why CPU sampling alone cannot account for all wall-clock delay
Sample-based CPU profiling captures on-CPU JavaScript only. It cannot tell you about:
- synchronous file reads waiting on the page cache or a network filesystem;
- TypeScript program construction happening partly in native code paths;
- libuv threadpool waits (and, for async native calls, the queue behind the default pool size);
- child processes or worker threads, unless you profile those separately.
So keep a wall-clock number beside the CPU number. If wall clock is 8 s and the JS profile accounts for 5 s, the missing 3 s is not a mystery to be reallocated — it is I/O, native time, or waiting, and it needs a different tool.
Turn Suspected ESLint Hotspots into Controlled Experiments
Disable one expensive rule or plugin at a time in a copied configuration while keeping the corpus and parser fixed
Change one variable per run. --rule lets you do this without editing the shipped config:
node bench/run.mjs src --no-cache --rule '{"<plugin>/<rule>":"off"}'
Or copy the config and delete exactly one entry:
cp eslint.config.mjs bench/eslint.minus-one.config.mjs
## edit the copy, remove one rule, change nothing else
node bench/run.mjs src --no-cache --config bench/eslint.minus-one.config.mjs
Record each delta in the evidence table. Also record what the rule did, because "14% faster without import/no-cycle" is a statement about a trade-off, not a free win.
Separate parsing and type-aware setup from rule execution without treating a different parser or configuration as an equivalent workload
This is the trap I see most often. Swapping @typescript-eslint/parser for espree makes a run faster and tells you nothing, because you have changed the workload: different AST shape, different tokens, different rules enabled, different semantics.
Legitimate separations:
- Same parser, type-aware rules off. Keeps the AST identical, removes the TypeScript program build. Measures what the type checker costs.
- Same parser and rules,
TIMING=1aggregate vs.--statsparse total. Splits parse from rule time within one workload. - Same everything,
--no-cachevs.--cache. Measures file-level caching, not code speed.
Illegitimate: "we replaced the parser and it got faster", "we disabled the plugin and it got faster, therefore the plugin should be native". Those are different workloads, and the second one is a semantic decision dressed as a performance one.
Compare autofix-disabled runs with fix-enabled passes and identify repeated work caused by fixes
node bench/run.mjs src --no-cache
node bench/run.mjs src --no-cache --fix-dry-run
--fix-dry-run executes the fix loop without writing files, so the difference is the cost of additional verify passes. If that difference is large, the interesting question is "why do fixes keep changing text on this corpus", and the answer might be two mutually conflicting rules, or a rule producing non-idempotent output. That is a bug-shaped finding, and fixing it can beat any native kernel.
Produce an evidence table linking each hypothesis to its profile evidence, controlled experiment, latency change, and semantic caveat
Worked example of the shape of this table. Every number here is a placeholder; fill it from your own runs before anyone quotes it.
| Hypothesis | Profile evidence | Controlled experiment | Δ median wall | Semantic caveat |
|---|---|---|---|---|
| One import-graph rule dominates | self time inside resolver frames under that rule | --rule '{"<plugin>/<rule>":"off"}' | <−x%> | removes a real correctness check |
| Type-aware setup dominates | inclusive time in TS program construction | same parser, type-aware rules off | <−y%> | different rule set; not equivalent workload |
| Fix loop re-lints repeatedly | files with >1 pass in stats summary | plain vs --fix-dry-run | <+z%> for fixes | files on disk unchanged in dry run |
| Dispatch is expensive | self time in selector dispatch | 50 no-op rules added | <+w%> | no-op rules still allocate closures |
| Parsing is the bottleneck | parser frames high inclusive + parse.total | none needed | n/a | tokens and comments still required |
Rule of thumb: a hypothesis that cannot produce a controlled experiment is not yet a hypothesis, it is a guess.
Estimate the Maximum Benefit Before Writing Rust
Apply Amdahl's law to a clearly hypothetical example: accelerating 20 percent of runtime fivefold yields only about 1.19 times overall speedup before integration costs
Amdahl's law: speedup = 1 / ((1 − p) + p/s), where p is the accelerated fraction and s the local speedup.
For p = 0.20, s = 5:
speedup = 1 / (0.80 + 0.20/5)
= 1 / (0.80 + 0.04)
= 1 / 0.84
≈ 1.190
And the ceiling, even with an infinitely fast kernel (s → ∞), is 1 / 0.80 = 1.25×. That is the number to put in the design doc.
| Accelerated share | s = 2 | s = 5 | s = 10 | s → ∞ |
|---|---|---|---|---|
| 10% | 1.053 | 1.087 | 1.099 | 1.111 |
| 20% | 1.111 | 1.190 | 1.220 | 1.250 |
| 30% | 1.176 | 1.316 | 1.370 | 1.429 |
| 50% | 1.333 | 1.667 | 1.818 | 2.000 |
Values computed from the formula above; no measurement required. Real integration costs — loading a .node, converting inputs, maintaining a second implementation — subtract from all of these.
Evaluate candidate kernels by measured runtime share, data volume, call frequency, determinism, and dependence on JavaScript objects
| Criterion | Wanted | Disqualifying |
|---|---|---|
| Runtime share | measurable, ideally ≥ 10–15% of wall clock | below noise floor |
| Data volume per call | kilobytes to megabytes | tens of bytes |
| Call frequency | once per file or once per pass | once per AST node |
| Determinism | pure function of its inputs | depends on mutable linter state |
| JS object dependence | operates on bytes, strings, or flat numeric arrays | needs the live AST, SourceCode, or plugin objects |
| Error semantics | can be expressed as thrown Error with a stable message | needs to call back into JS to construct diagnostics |
The last row is the one that always bites. If the kernel's job includes producing context.report() calls, it is not a kernel, it is a rewrite of the rule engine.
Reject weak native boundaries: per-node callbacks, whole-AST conversion, or repeated transfers that retain most work in JavaScript
Three anti-patterns, all of which I have seen proposed:
Per-node callbacks. A native traversal that calls a JS function for each node. Every call pays napi call overhead plus, depending on the shape, argument marshalling. For small node handlers this is slower than the pure JS version, sometimes dramatically.
Whole-AST conversion. Serialising an ESTree AST into a Rust structure and back. The conversion cost scales with the exact thing you are trying to make cheap, and you now maintain two AST definitions that must stay in lockstep with every parser change.
Chatty transfers. Calling a Uint8Array kernel per token, or per rule, or per node type. Measure the boundary cost first: on typical hardware a trivial napi call with a small typed array argument costs on the order of microseconds, not nanoseconds. Multiply by millions of calls and the budget is gone before any work happens. Your exact number is hardware- and napi-rs-version-dependent — measure it rather than quoting mine.
Try lower-cost JavaScript changes first, including avoiding repeated computation, reducing allocations, and narrowing rule work where semantics allow
Before the first line of Rust, exhaust the cheap options:
- Cache per-file lookups inside a rule. Rules that re-walk the token stream on every node hit are common and fixable.
- Reduce allocations in the hot pass. Reuse arrays, avoid
Object.entriesin tight loops, drop intermediate strings. - Narrow rule scope. Many configs enable expensive rules on paths they never needed to cover. Restricting
filespatterns is a one-line change. - Fix the fix loop. If
files with >1 passis high, find the non-idempotent rule. - Check the type-aware setup. Reusing a single program across files, or avoiding type-aware rules where they earn little, is usually worth more than any kernel.
- Check the cache. A CI job that never restores
.eslintcacheis paying full price every run.
Every one of these keeps the plugin API intact, ships as a normal JavaScript release, and needs no cross-compilation matrix.
Prototype One Bounded napi-rs Hotspot
Choose an actual candidate from the profile; if none qualifies, stop rather than inventing a native optimization opportunity
This is the hardest instruction in the post to follow, so I am stating it plainly: if your profile does not show a pure, coarse-grained, high-share function, stop here. Write up the profiling results, ship the JavaScript improvements, and revisit in six months. A native module that accelerates a function nobody's profile flagged is a maintenance liability with a benchmark attached.
If you do have a candidate, it will look like this: a function that takes a buffer or a flat array, does substantial work per byte or per element, returns a buffer or a flat array, and appears in your profile with real self time.
Define a coarse-grained API with explicit inputs, outputs, error behavior, ownership, and a JavaScript reference implementation
The contract comes first, in TypeScript, with the reference implementation written and tested before Rust exists:
// A coarse-grained kernel: one call per file, no callbacks, flat data out.
// Returns, for each name, how many times it appears as a member expression
// property in the given source bytes. Pure function of its inputs.
export function countMemberProperties(
source: Uint8Array,
names: readonly string[],
): Uint32Array;
Contract points to pin down explicitly:
- Ownership:
sourceis read-only; the returnedUint32Arrayis freshly allocated and owned by the caller. - Errors: invalid UTF-8, or
nameslonger than the input, throwsErrorwith a stable message. No partial results. - Determinism: identical inputs produce identical output, byte for byte.
- Locality: no filesystem, no clock, no globals, no callbacks. That is what makes it testable and thread-safe.
- Semantics: documented precisely, including the cases your JavaScript version already handles (comments, strings, regex literals). This is the part where "fast" turns into "wrong".
Plan a minimal Rust export, JavaScript adapter, and pinned build commands using documented napi-rs APIs without implying this is ESLint's reported implementation
This is a sketch of the shape of a napi-rs module, not a claim about what ESLint is doing.
[package]
name = "lint-kernel"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
napi = { version = "2", default-features = false, features = ["napi8"] }
napi-derive = "2"
[build-dependencies]
napi-build = "2"// src/lib.rs — sketch. Real version needs bounds checks and error handling.
use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi]
pub fn count_member_properties(source: Buffer, names: Vec<String>) -> Result<Uint32Array> {
let bytes = source.as_ref();
let mut counts = vec![0u32; names.len()];
for (i, name) in names.iter().enumerate() {
// trimmed: real implementation must respect string/comment/regex boundaries
counts[i] = count_occurrences(bytes, name.as_bytes()) as u32;
}
Ok(counts.into())
}
fn count_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
if needle.is_empty() || needle.len() > haystack.len() { return 0; }
haystack.windows(needle.len()).filter(|w| *w == needle).count()
}
Build and inspect what was produced:
npm i -D @napi-rs/cli
npx napi build --platform --release
node -e "const k=require('./lint-kernel.linux-x64-gnu.node'); console.log(Object.keys(k))"
The JS adapter keeps the fast path optional and the reference implementation authoritative:
// adapter picks native when available, otherwise the reference implementation
const { countMemberProperties: reference } = require("./reference.js");
let native = null;
try {
native = require("./lint-kernel.linux-x64-gnu.node");
} catch (err) {
// log once; a broken install must not break linting
}
module.exports.countMemberProperties = native
? (source, names) => native.countMemberProperties(Buffer.from(source), names)
: reference;
Two things that will surprise you: the version pinning in napi / napi-derive / napi-build matters, because generated bindings and the CLI must agree; and --platform embeds a platform-specific filename, which is exactly what you want for packaging and exactly what breaks if you check .node files into git.
Measure boundary-only overhead, input conversion, native execution, output conversion, and the complete integrated call separately
Do not report one number. Report five:
| Measurement | How |
|---|---|
| Boundary-only | export a noop(source, names) that validates nothing and returns a zero-filled array; time it with the same inputs |
| Input conversion | difference between noop with real inputs and noop with a 1-byte input |
| Native execution | wall clock inside Rust via std::time::Instant, exposed behind a temporary debug export |
| Output conversion | compare a kernel returning Uint32Array against one returning Vec<u32> (array of numbers) |
| Full integrated call | JS-side timer around the adapter, called from a real lint run |
The noop comparison is the single most useful one. If noop with your real 2 MB input costs 0.4 ms and the kernel costs 0.9 ms, you are spending 30% of the win on marshalling and the design needs another look. Returning a typed array instead of a boxed array is usually the largest single conversion lever.
Explain synchronous blocking, asynchronous execution costs, and why napi-rs does not automatically parallelize ESLint rule execution
A #[napi] function without async runs synchronously on the JS thread. That is often correct: a 200 µs kernel runs faster than any scheduling mechanism, and blocking briefly is cheaper than a thread hop.
Asynchronous execution (napi-rs AsyncTask / napi::Task, or an async runtime feature) moves work to the libuv threadpool. Costs to measure, not assume:
- a queue-and-wake round trip, typically tens of microseconds;
- input that must be owned or copied to be sent across threads — no JS object access off the main thread;
- contention with other threadpool users. Node's default pool is small (
UV_THREADPOOL_SIZE), and if the linter's own I/O path is synchronous, the pool may be mostly idle — which you should verify rather than assume.
For a sub-millisecond kernel, async is usually a pessimisation. For a 50 ms kernel, it is free parallelism on paper and needs measuring.
And the important non-claim: napi-rs does not parallelize ESLint. Rule execution is interleaved with a single traversal in a single JS isolate, and rule listeners receive context objects full of JavaScript references. No amount of Rust changes that. Parallelism in ESLint comes from running files concurrently, at the process or worker-thread level, which is an architectural change independent of the language.
Verify Semantic Compatibility Before Calling It Faster
Differential-test native and JavaScript implementations on ordinary inputs, malformed inputs, Unicode, and boundary cases
Differential testing is non-negotiable. Same inputs, both implementations, assert deep equality:
// test/differential.test.js
const cases = [
["", ["a"]],
["a.b.c;", ["b", "c"]],
["obj . prop", ["prop"]], // whitespace around the dot
["'a.b'", ["b"]], // inside a string literal
["// a.b\nx;", ["b"]], // inside a comment
["const \u00e9 = 1; caf\u00e9.x;", ["x"]], // non-ASCII identifiers
["\uFEFFa.b", ["b"]], // byte-order mark
["\uD83D\uDE00.b", ["b"]], // astral plane character
["a".repeat(10_000), ["a"]], // large input
];
for (const [source, names] of cases) {
test("parity: " + JSON.stringify(source).slice(0, 40), () => {
const bytes = Buffer.from(source, "utf8");
assert.deepEqual(
Array.from(native(bytes, names)),
Array.from(reference(bytes, names)),
);
});
}
Then go further than the unit cases: fuzz with random byte strings, and run both implementations over every file in your fixed corpus and diff the outputs. Byte-level kernels are where surrogate pairs, BOMs, and truncated UTF-8 produce silent divergence.
Compare lint diagnostics, source locations, fix ranges, output ordering, and error behavior across the fixed corpus
Function parity is not linter parity. Snapshot the full diagnostic stream from both paths and compare field by field:
| Field | Why it can diverge |
|---|---|
ruleId, messageId | different code path picking a different branch |
message | interpolated values, e.g. identifier names |
line, column, endLine, endColumn | off-by-one in byte vs. character offsets — bites hardest with non-ASCII |
fix.range, fix.text | different replacement text or range width |
| suggestion arrays | ordering, missing entries |
| message ordering | ESLint sorts by position; a native path that reports in a different order changes output |
| exit code and stderr | new failure modes: missing binary, load error, wrong platform |
A workable harness: run the CLI twice — once with the native path enabled, once with the reference implementation forced via an env flag — write both JSON reports, and diff them with a normaliser that drops filePath prefixes.
Column numbers are the highest-yield field in that table. Byte offsets and UTF-16 code-unit offsets diverge on any file containing non-ASCII text, and the bug only appears on the files nobody put in the fixtures.
Re-run unchanged JavaScript plugins and parsers, documenting any public API or observable behavior differences
If your change is a kernel behind a rule, the plugin surface should be untouched — prove it. Run a corpus with third-party plugins and custom parsers enabled, and record:
- plugin load order and any load warnings;
- custom parser output identical to the previous run (AST hash or serialised diff on a sample);
- formatter output byte-identical;
--fixresults byte-identical on a scratch copy of the corpus.
If any of these differ, you have changed public behaviour. That is a breaking change with a performance footnote, and it needs a migration story, not a benchmark.
Benchmark the Integrated ESLint Run, Not Just the Rust Function
Repeat the original baseline matrix with native and JavaScript paths under identical conditions
Same machine, same corpus, same lockfile, same ESLint cache state, same concurrency setting, same environment file. Interleave the runs rather than doing all-native then all-JS — thermal drift and background processes do not care about your experimental design:
for i in 1 2 3 4 5; do
LINT_KERNEL=js node bench/run.mjs src --no-cache
LINT_KERNEL=native node bench/run.mjs src --no-cache
done
Present measured end-to-end latency, CPU time, memory, startup cost, and correctness results alongside isolated kernel timings
Report all of it, including the parts that look bad:
| Metric | JS path | Native path | Note |
|---|---|---|---|
| Kernel-only time | <...> | <...> | the flattering number |
| End-to-end median | <...> | <...> | the number that matters |
| Startup delta | — | <...> | .node load + init |
| Peak RSS | <...> | <...> | native heaps are outside V8's accounting |
| Diagnostic diffs | 0 | <...> | must be 0 to claim parity |
| Install failures, supported matrix | 0 | <...> | measured in CI, not locally |
If the end-to-end gain is much smaller than the kernel gain, that is not a failure of measurement, it is Amdahl asserting itself. Report it that way.
Explain regressions and uncertainty: small repositories, cache-hit runs, noisy measurements, and workloads outside the optimization's scope
Expect regressions in these cases, and say so before someone else finds them:
- Small repositories. Startup and
.nodeloading dominate; the kernel runs for microseconds. - Cache-hit runs. If ESLint's cache means most files are skipped, the kernel never runs, but you still pay the load cost.
- Noisy machines. A 3% end-to-end change is indistinguishable from fan noise on a laptop. Run enough repetitions and report the spread.
- Out-of-scope configs. A repository that does not use the rule you optimised sees exactly zero benefit and a nonzero load cost.
- Different Node versions. Node-API gives you ABI stability, not identical performance.
Account for Native Distribution and Maintenance Costs
Define the supported operating-system, architecture, libc, and Node.js matrix; distinguish Node-API compatibility from platform portability
Node-API buys you source-free ABI stability across Node versions. It buys you nothing across operating systems, CPU architectures, or libc. You still ship one binary per cell in this table:
| OS | Arch | libc | Package target |
|---|---|---|---|
| Linux | x64 | glibc | <pkg>-linux-x64-gnu |
| Linux | x64 | musl | <pkg>-linux-x64-musl |
| Linux | arm64 | glibc / musl | <pkg>-linux-arm64-gnu / -musl |
| macOS | x64 / arm64 | system | <pkg>-darwin-x64 / -arm64 |
| Windows | x64 | MSVC runtime | <pkg>-win32-x64-msvc |
Each cell needs a build runner, a CI job, and someone to notice when it breaks. Alpine users will find the musl gap within a week of release; that is the most common distribution incident I know of in this space.
Plan prebuilt packages, installation checks, unsupported-platform behavior, and whether a JavaScript fallback is practical
- Prebuilt per-platform packages as optional dependencies, with the loader resolving the right one. This is the established pattern and napi-rs's CLI is built around it.
- An explicit unsupported-platform path. Either fall back to JavaScript (with a one-time warning) or fail loudly at install with a clear message. Silent fallback that nobody notices means your benchmark numbers and your users' numbers diverge permanently.
- A JavaScript fallback is usually practical for a pure kernel. You wrote the reference implementation first — that decision pays off here. If the fallback is not practical, the kernel was probably not pure, and that is a design signal.
- Postinstall checks. A
.nodecompiled against a different glibc or linked against a missing shared library fails atrequiretime with a message most users cannot act on. Wrap the load and print something diagnostic.
Add CI coverage for native loading, semantic parity, packaging, Rust dependency updates, and debugging across the language boundary
Minimum CI surface:
## .github/workflows/native.yml (sketch)
jobs:
parity:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx napi build --platform --release
- run: node -e "require('./lint-kernel.linux-x64-gnu.node')"
- run: npm test # differential tests
- run: node bench/diff-diagnostics.mjs # corpus-level parity
package:
runs-on: ubuntu-latest
steps:
- run: npm pack
- run: npm i -g ./lint-kernel-*.tgz && node -e "require('lint-kernel')"
audit:
runs-on: ubuntu-latest
steps:
- run: cargo audit
Plus a cross-platform matrix job that only does the load test — that is cheap and catches the packaging class of failure early. And keep a debugging path: symbols available for the release binaries, and a documented way to run with the JavaScript fallback so an incident does not require rolling back a release.
Make the Go or No-Go Decision from Evidence
Set project-specific acceptance criteria for end-to-end gains, compatibility, installation reliability, and ongoing maintenance cost
Criteria written before the prototype, because afterwards you will rationalise whatever you got:
| Criterion | Suggested bar | Evidence source |
|---|---|---|
| End-to-end median gain | ≥ 8–10% on two real corpora | interleaved baseline matrix |
| Diagnostic parity | exactly zero diffs | corpus-level diff harness |
| Public API parity | zero observable changes | plugin/parser regression suite |
| Install reliability | 100% on supported matrix | CI matrix + packaging job |
| Fallback | works and is tested | CI with native load disabled |
| Maintenance | named owner, ≤ 1 release cycle per quarter | your team's actual capacity |
| Regression budget | bounded and documented | startup and small-repo benchmarks |
The maintenance row is the one people omit and later regret. A native addon is a second build system, a second dependency ecosystem, and a second debugging toolchain. If nobody owns it, it will be stale within a year — and a stale native binary is worse than slow JavaScript, because it fails at load time.
Conclude with the measured decision: retain JavaScript, optimize JavaScript first, or adopt one native kernel without claiming the supplied report proves a speedup
Three defensible outcomes, and all three are legitimate results:
- Retain JavaScript. Your profile showed no dominant, pure, coarse-grained kernel. Ship nothing. Publish the profile as documentation of where time actually goes.
- Optimise JavaScript first. Most likely outcome for most repositories. Fix the fix loop, reduce allocations, narrow rule scope, cache per-file computations, restore the ESLint cache in CI — then re-profile and see what is left.
- Adopt exactly one native kernel. Justified when a measured share of wall clock is large, the function is pure, the boundary is coarse, end-to-end gains clear the bar above, and the distribution matrix is genuinely covered.
None of those outcomes is "ESLint is moving to Rust, so we should too." The supplied report does not even establish that ESLint is doing that — it says a full rewrite was rejected while napi-rs modules were being experimented with, which is a much narrower statement. The transferable part is the method: profile the pipeline, price the boundary, apply Amdahl before you write code, and keep the plugin API untouched.
If you take one thing from this post, take the ceiling calculation. A native kernel that halves the cost of 20% of your runtime buys you 1.11×, and then you own a cross-compilation matrix forever.
Further Reading
Preserve the supplied MLQ.ai discovery link as secondary reporting and distinguish its claims from independently verified documentation
- MLQ.ai item, "ESLint Creator Rejects Full Rust Rewrite, Tests napi-rs Modules" — secondary reporting via a Google News RSS redirect, dated 2026-12-05. Treat the rewrite decision and the napi-rs experimentation as reported claims, not verified facts.
Link official ESLint documentation for rule timing, statistics, custom parsers, and custom rules
- ESLint: Profile Rule Performance — the
TIMING=1environment variable and its limits. - ESLint: Command Line Interface Reference —
--stats,--cache,--fix-dry-run,--print-config, and current concurrency flags. - ESLint: Custom Parsers — what a parser must return (AST, tokens, comments, locations, ranges).
- ESLint: Custom Rules — the visitor and
context.report()contract your native work must not disturb. - eslint/espree and eslint/eslint-scope — the parser and scope analyser that show up in your profiles.
Link official Node.js documentation for CPU profiling and Node-API, plus napi-rs documentation for APIs, builds, and cross-platform distribution
- Node.js CLI:
--cpu-prof— profile output, sampling interval, and directory options. - Node.js: Node-API — ABI stability guarantees, versioning, and what Node-API does not promise about portability.
- Node.js CLI:
UV_THREADPOOL_SIZE— the threadpool your async native calls compete for. - napi-rs: Getting Started — crate layout,
#[napi]macro, and the CLI build flow. - napi-rs repository — current API surface, examples, and release notes for the version you pin.
More posts

Laravel Rust Beta: What Familiar Branding Does and Doesn’t Buy You in a JSON API
Assessing Laravel's Rust beta by building a small JSON API to separate familiar branding from real compatibility across routing, application structure, ecosystem maturity, and deployment, while distinguishing Laravel Cloud's multi-language expansion from framework adoption decisions.

Testing TypeScript 7.1 Against Framework Integrations with a CI Compatibility Gate
Build a CI compatibility gate that exercises TypeScript 7.1's restored compiler APIs and framework integrations against your tooling, and pins the exact release stage since coverage alternates between beta and release-candidate labels.

Why a Pre-Request Balance Check Overspends Under Concurrent LLM Calls in Node.js
A deep dive into why a pre-request balance check silently overspends when concurrent Node.js calls race the same tenant budget, and how atomic reservations, post-call reconciliation, and streaming-aware accounting close the gap.
Loading comments…