Skip to content

refactor(performance-optimization): move Step 3 code patterns into a skill-local reference (-25% tokens per load) - #580

Merged
addyosmani merged 2 commits into
addyosmani:mainfrom
Syamsuddin:trim/performance-optimization-references
Oct 3, 2026
Merged

addyosmani merged 2 commits into
addyosmani:mainfrom
Syamsuddin:trim/performance-optimization-references

Conversation

@Syamsuddin

Copy link
Copy Markdown
Contributor

Why

Second in the series started by #579. performance-optimization/SKILL.md sat at 496 lines / 3,314 words (~4.3k tokens), just under the 500-line budget in docs/skill-anatomy.md and the largest skill after security-and-hardening. Step 3 ("Fix Common Anti-Patterns") alone was ~1,800 words of worked TypeScript, SQL, HTML, and TSX — material an agent only needs once Step 2 has named the bottleneck, but paid for on every activation.

What changed

skills/performance-optimization/SKILL.md — 496 → 267 lines, 3,314 → 2,488 words

  • Lines 1–120 (frontmatter, Overview, When to Use, CWV targets, workflow, Step 1, the measurement decision tree, Step 2 tables) and everything from Step 4 onward (Verify, Guard, See Also, Rationalizations, Red Flags, Verification) are byte-identical to main. No description edit, so routing is untouched.
  • Step 3 is replaced by a condensed "Fix the Bottleneck" list: each anti-pattern's rule and its recognizable signature, with a deep link to the worked fix. Every rule the later sections depend on is still stated inline — read the plan before adding an index and revert one that didn't change it; cache key includes every input that changes the response; one invalidation strategy; stampede protection; a bigger pool relocates the queue; memo/useMemo overuse is its own cost.

skills/performance-optimization/references/optimization-patterns.md (new, 250 lines)

Verification

  • node scripts/validate-skills.js — 25 skills, 0 errors, 0 warnings
  • node scripts/validate-reference-links.js — pass
  • node scripts/run-evals.js --min-rank1 95 — rank-1 100% (88/88), no collision warnings
  • All 8 #anchor links resolve; every heading in the new file is linked from SKILL.md
  • The behavioral eval's expectations (measure before optimizing, target the measured bottleneck, verify against baseline, add a guard) all live in Steps 1, 2, 4, 5, which are unchanged

Coordination with #492

#492 touches this file in two places: the "Slow API responses" row of the Step 2 Backend table and a paragraph inserted after the See Also sentence. Both context regions are untouched here, so #492's hunks still apply on top of this in either merge order.

🤖 Generated with Claude Code

…skill-local reference

SKILL.md loaded ~4.3k tokens on every activation at 496 lines, just
under the 500-line budget in docs/skill-anatomy.md, with Step 3 ("Fix
Common Anti-Patterns") alone at ~1,800 words of worked TypeScript, SQL,
HTML, and TSX that an agent only needs once Step 2 has named the
bottleneck.

Move Step 3's body verbatim into references/optimization-patterns.md
(same convention as constraint-driven-development/references/floor-guard.md
and addyosmani#579), promoting its #### headings to ## so the file stands alone.
SKILL.md keeps the workflow and replaces Step 3 with a condensed list:
each anti-pattern's rule and recognizable signature, with a deep link to
its worked fix. Every rule the Red Flags, Rationalizations, and
Verification sections rely on (read the plan before indexing, cache key
includes the viewer, bigger pool is not faster, neutral is a revert) is
still stated in SKILL.md.

Lines 1-120 (frontmatter through the Step 2 tables) and Step 4 onward
are byte-identical to before, so the two hunks in addyosmani#492 still apply.

SKILL.md: 496 -> 267 lines, 3314 -> 2488 words (~-25% tokens per load).
Routing unchanged: run-evals rank-1 stays 100%, no description edits.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

@nucliweb nucliweb left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The move is faithful and I'd be comfortable with it once the condensed Step 3 is tightened in three places. I wrote the query-plan and caching sections in #521, so I read the new bullets against what those tables teach; that list is now the only thing an agent sees unless it opens the link, and one bullet says something the reference file contradicts.

What I ran, on a test-merge against c004a74: validate-skills 25 skills 0 errors, validate-reference-links pass, the rest of the CI set green locally (no checks have run on the PR itself yet). The moved body diffs identical to the old range after the declared normalizations, lines 1-120 and Step 4 onward are byte-identical, all 8 anchors resolve, and #492 merges clean in both orders with identical trees. Leaving Steps 4 and 5 untouched was the right call, it made this checkable.

The three things before it lands:

  • "An index will not help a low-selectivity dominant value, a leading wildcard, or a function applied to the column" drops the qualifiers from the table it summarizes, which says "needs trigram or full-text" and "index the expression instead". As written, an agent that doesn't open the link concludes no index fixes WHERE lower(email) = ?. Suggested: "A plain B-tree index will not help a low-selectivity dominant value (a partial index serves the rare value), a leading wildcard (needs trigram or full-text), or a function applied to the column (index the expression)."
  • The three plan signatures are listed, but "each call for a different fix" no longer says which. The one worth keeping inline is that a rows= estimate off by an order of magnitude means stale statistics, because its fix is ANALYZE rather than an index, which is the point of the section.
  • Red Flags still audits "a cache with no stated staleness window", but the rule that teaches it (state the acceptable window explicitly) now lives only in the reference. A few words in the caching bullet cover it.

One non-blocking note on the headline, which applies to #579 too: -25% is the number for the path where the reference is never opened (-24.9% by words, confirmed). Opened whole, the activation costs about 17% more than main, since the condensed list is 511 words of new prose on top of the 1,399 moved, and the skill's own trigger prompts (N+1, indexes, LCP) are all Step 3 topics. I'd lead with the 500-line headroom instead (496 to 267, with #492 about to add lines), which holds unconditionally, and tell the agent to read the one section it needs rather than the whole file. The 88/88 doesn't speak to this change either way, since routing ranks on name and description only; #584 covers what the evals can observe for skill-local references.

Whether the catalog wants this split applied skill by skill as a series is a direction question rather than a quality one, so I'll leave that to @addyosmani. Placement itself matches skill-anatomy, same shape as floor-guard.md.

@addyosmani

Copy link
Copy Markdown
Owner

The move itself is faithful, I checked, nothing is lost since the full detail lives in the reference. Before I merge, please address nucliweb's three points on the condensed Step 3 summary. One is a real correctness issue: as written, the shortened index bullet drops the qualifiers, so an agent that doesn't open the reference could wrongly conclude no index helps a WHERE lower(email)=? query. Same for the stale-stats-means-ANALYZE case, and the cache-staleness Red Flag that now only lives in the reference. Small wording fixes to the summary and it's ready. Thanks for doing this, it pairs well with the context-size direction in #433.

addyosmani pushed a commit that referenced this pull request Sep 23, 2026
…es/ files (#585)

A file under skills/<name>/references/ sits one directory deeper than SKILL.md, so a link to a shared checklist needs ../../../references/ from there. The validator only read SKILL.md, which left that off-by-a-level mistake unguarded in the one place it can now happen (hardening-patterns.md on main, optimization-patterns.md in #580).

The rule is unchanged: only references/*.md links, fenced blocks exempt, paths that do not exist yet ignored. The file set grows to include the markdown files directly inside each skill's references/ directory, and every link resolves from the file that contains it. The failure hint names the three-level prefix when the violation is in a reference file.

@abhisheksharma2411 abhisheksharma2411 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Syamsuddin — a content-moving refactor is the one shape where "looks fine" and "is fine" come apart quietly, so I checked it mechanically rather than by reading. It's clean. Details, since that's what makes the approval worth anything.

Nothing was lost

Diffed every line removed from SKILL.md against the new tree (reference + SKILL.md, whitespace-normalized). 240 removed lines; every one of them lands somewhere, including the easy-to-drop prose:

**Do not cache:** anything whose staleness is a correctness bug (balances, permissions, inventory at checkout)…

That one is in the reference intact. The only line genuinely absent is the old ### Step 3: Fix Common Anti-Patterns heading itself, which is correct — Step 3 is still there as "Fix the Bottleneck", so the numbered process still runs 1→5 with no gap. A refactor that left a 2→4 jump is the version of this I was expecting to find.

All eight deep-link anchors resolve

This is the part a link checker misses — validate-reference-links.js confirms the file exists, not the #fragment. Generated the GitHub slugs from the reference's own headings and matched them against every link in SKILL.md:

OK  #n1-queries-backend                 OK  #missing-caching-backend
OK  #unbounded-data-fetching            OK  #missing-image-optimization-frontend
OK  #queries-that-ignore-their-index    OK  #unnecessary-re-renders-react
OK  #connection-pool-exhaustion         OK  #large-bundle-size

broken anchors: 0

Worth noting #n1-queries-backend in particular: #### N+1 Queries (Backend) slugs with the + dropped, so the intuitive #n+1-queries would have been wrong. Whoever wrote these got it right.

Gates

validate-skills.js — 25 skills, 0 errors, 0 warnings. validate-reference-links.js — 25 skills, 0 errors. SKILL.md 496 → 267 lines, 3,314 → 2,488 words; reference 250 lines / 1,399 words.

One observation, not a request

The summary-plus-deep-link shape in Step 3 is better than the usual "see the reference" pointer: each bullet carries the rule and the recognition signature, so an agent that already knows the pattern never opens the file, and one that doesn't gets a precise destination. That's the version of this refactor that actually saves tokens rather than moving them — worth saying, because the next person doing the third in the series should copy this structure rather than the file split alone.

Nothing blocking.

@addyosmani addyosmani left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrapped nucliweb's three points into two one-click suggestions so this is quick to land. Apply the first and it's ready to merge; the second is worth taking too. The move itself checks out, nothing was dropped.

| Versioned keys (`user:42:profile:v7`) | Never invalidate, just stop reading old keys. Costs memory until eviction |
- **N+1 queries.** One query per row is the most common backend bottleneck. Fetch the relation in the same query (join/include) instead of in the loop. [Pattern](references/optimization-patterns.md#n1-queries-backend).
- **Unbounded data fetching.** Every list endpoint paginates with a limit and a stable order. [Pattern](references/optimization-patterns.md#unbounded-data-fetching).
- **Queries that ignore their index.** "Add an index" is the guess; `EXPLAIN ANALYZE` is the measurement. A `Seq Scan` where you expected an index, a `rows=` estimate off by an order of magnitude, and a `Sort` node above the scan each call for a different fix. Index for the shape of the query (equality columns first, then the range or sort column). An index will not help a low-selectivity dominant value, a leading wildcard, or a function applied to the column, and every index taxes every write. Re-run the plan afterwards; an index that did not change it is a revert. [Pattern](references/optimization-patterns.md#queries-that-ignore-their-index).

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (blocking): as written, an agent that doesn't open the reference would conclude no index helps WHERE lower(email) = ?, and it loses the stale-stats case (bad rows= means ANALYZE, not an index). This folds nucliweb's first two points back in:

Suggested change
- **Queries that ignore their index.** "Add an index" is the guess; `EXPLAIN ANALYZE` is the measurement. A `Seq Scan` where you expected an index, a `rows=` estimate off by an order of magnitude, and a `Sort` node above the scan each call for a different fix. Index for the shape of the query (equality columns first, then the range or sort column). An index will not help a low-selectivity dominant value, a leading wildcard, or a function applied to the column, and every index taxes every write. Re-run the plan afterwards; an index that did not change it is a revert. [Pattern](references/optimization-patterns.md#queries-that-ignore-their-index).
- **Queries that ignore their index.** "Add an index" is the guess; `EXPLAIN ANALYZE` is the measurement. A `Seq Scan` where you expected an index, a `rows=` estimate off by an order of magnitude, and a `Sort` node above the scan each call for a different fix; a bad `rows=` estimate means stale statistics, so run `ANALYZE` rather than adding an index. Index for the shape of the query (equality columns first, then the range or sort column). A plain index will not help a query on a low-selectivity dominant value (a partial index serves the rare value), a leading wildcard (needs trigram or full-text), or a function applied to the column (index the expression, as in `WHERE lower(email) = ?`), and every index taxes every write. Re-run the plan afterwards; an index that did not change it is a revert. [Pattern](references/optimization-patterns.md#queries-that-ignore-their-index).

- **Unbounded data fetching.** Every list endpoint paginates with a limit and a stable order. [Pattern](references/optimization-patterns.md#unbounded-data-fetching).
- **Queries that ignore their index.** "Add an index" is the guess; `EXPLAIN ANALYZE` is the measurement. A `Seq Scan` where you expected an index, a `rows=` estimate off by an order of magnitude, and a `Sort` node above the scan each call for a different fix. Index for the shape of the query (equality columns first, then the range or sort column). An index will not help a low-selectivity dominant value, a leading wildcard, or a function applied to the column, and every index taxes every write. Re-run the plan afterwards; an index that did not change it is a revert. [Pattern](references/optimization-patterns.md#queries-that-ignore-their-index).
- **Connection pool exhaustion.** Signature: *every* endpoint slows at once, time is spent waiting for a connection rather than executing, and the database shows mostly idle sessions. One pool per process, sized so `instances × max` stays under the database's connection ceiling. Bigger is not faster; it relocates the queue to the database where it is harder to see. With unbounded instance counts (serverless, autoscaling), multiplex through a proxy (pgbouncer, RDS Proxy) instead of raising `max`. [Pattern](references/optimization-patterns.md#connection-pool-exhaustion).
- **Missing caching.** Cache what is expensive to produce and read far more often than it changes; caching an already-fast query adds a network hop and a staleness bug in exchange for nothing. Pick the layer deliberately (in-process, shared, CDN). Every input that changes the response belongs in the key (tenant, locale, permissions, feature flags): a key that omits the viewer is how one user's data gets served to another. Choose one invalidation strategy (TTL, event or tag based, versioned keys). Guard hot keys against the stampede: serve stale while one request recomputes, or coalesce concurrent misses behind a single in-flight promise. Never cache what must be fresh (balances, permissions, inventory at checkout). [Pattern](references/optimization-patterns.md#missing-caching-backend); request coalescing, write strategies, and negative caching in `../../references/performance-checklist.md`.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): the Red Flag at line 239 audits "a cache with no stated staleness window", but that rule now only lives in the reference. One clause keeps the body self-consistent:

Suggested change
- **Missing caching.** Cache what is expensive to produce and read far more often than it changes; caching an already-fast query adds a network hop and a staleness bug in exchange for nothing. Pick the layer deliberately (in-process, shared, CDN). Every input that changes the response belongs in the key (tenant, locale, permissions, feature flags): a key that omits the viewer is how one user's data gets served to another. Choose one invalidation strategy (TTL, event or tag based, versioned keys). Guard hot keys against the stampede: serve stale while one request recomputes, or coalesce concurrent misses behind a single in-flight promise. Never cache what must be fresh (balances, permissions, inventory at checkout). [Pattern](references/optimization-patterns.md#missing-caching-backend); request coalescing, write strategies, and negative caching in `../../references/performance-checklist.md`.
- **Missing caching.** Cache what is expensive to produce and read far more often than it changes; caching an already-fast query adds a network hop and a staleness bug in exchange for nothing. Pick the layer deliberately (in-process, shared, CDN). Every input that changes the response belongs in the key (tenant, locale, permissions, feature flags): a key that omits the viewer is how one user's data gets served to another. Choose one invalidation strategy (TTL, event or tag based, versioned keys) and state the acceptable staleness window explicitly. Guard hot keys against the stampede: serve stale while one request recomputes, or coalesce concurrent misses behind a single in-flight promise. Never cache what must be fresh (balances, permissions, inventory at checkout). [Pattern](references/optimization-patterns.md#missing-caching-backend); request coalescing, write strategies, and negative caching in `../../references/performance-checklist.md`.

… and staleness window in Step 3

Applies the review suggestions on addyosmani#580, which carry nucliweb's three points:
the condensed index bullet lost the partial, trigram/full-text and expression
index qualifiers, it no longer said a bad rows= estimate means ANALYZE, and
the caching bullet dropped the staleness window the Red Flags still audit.

Co-authored-by: Joan León <nucliweb@users.noreply.github.com>

@addyosmani addyosmani left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

praise: the move was faithful from the start, and with nucliweb's three points now applied (the index qualifiers including the expression index, bad rows= means ANALYZE, and the staleness window the Red Flags audit) the condensed Step 3 says the right thing on its own. I pushed those as a small commit on your branch to unblock it, credit to nucliweb for the substance. SKILL.md goes from 496 to 267 lines, all checks green. Merging, thank you.

@Syamsuddin

Copy link
Copy Markdown
Contributor Author

Thanks @nucliweb, @abhisheksharma2411, and @addyosmani for the careful review. Applied both suggestions. Also reworded the title/description to lead with the line-budget headroom instead of the -25% figure, since as nucliweb noted that number only holds when the reference isn’t opened. Will carry the “rule + signature + deep link” structure forward to the next one in the series.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants