agentleFS
nurmdrafinurmdrafi/pi-native/skills/api-performance/SKILL.md

api-performance

Skill4 starsChanged 23 days agoMITView on GitHub

Fixes N+1 request fan-out and protects upstreams behind proxy, aggregator and image-fetch routes: reads the observability signal (Sentry N+1 API Call insight, span counts), finds whether repeats come from browser refetching or concurrent duplicate misses, and applies the fix ladder — HTTP cache headers, in-flight dedupe, bounded TTL cache, batch endpoint. Use when a route is called once per rendered item, profiling shows repeated upstream calls, a response carries no-store, an icon/asset/geocode proxy is slow under load, or an APM insight names a route as N+1. NOT for choosing a cache library (→ ponytail) or map icon loading specifics (→ map-integration).

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Check the cheap explanation before the clever one: a pass-through route that sets Cache-Control: private, no-store (or inherits a no-cache …

    line 22
  2. Distinctive:

    4. Batch: When one view needs many keys, a single endpoint that accepts a list beats N calls that are each cached well.

    line 58
  3. Distinctive:

    Never let a client-supplied URL reach the cache without the same allowlist check the route already enforces.

    line 65
  4. Distinctive:

    Write the three tests before the code — concurrent collapse (one upstream call for two simultaneous requests), cached repeat (second …

    line 69

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

N+1 fan-out and route-level caching

One page render asks for N items; each item reaches the server separately, and the server forwards each one upstream. Latency multiplies, the upstream sees a concurrent burst, and a single user can generate the load of a hundred.

Two independent causes, two different fixes. Identify which one you have before touching code.

CauseEvidenceFix
Repeats over time — the same URL requested again on every renderResponse carries no-store; browser network panel shows the identical request each timeCache headers (step 1)
Repeats at the same instant — a burst of identical requests before any response landsConcurrent server spans for the same key; upstream sees clone callsIn-flight dedupe (step 2)
Many distinct keys for one viewN different URLs from one page, each cheap but summed expensiveBatch endpoint or TTL cache (steps 3–4)

Read the signal first

APM tools surface this pattern under names like "N+1 API Call" with the route pattern attached (for Sentry: Performance → Insights, route normalized as /api/...?key=*). Confirm the count against the route's own spans before optimizing: one insight row naming a route proves repeats exist, not why.

Check the cheap explanation before the clever one: a pass-through route that sets Cache-Control: private, no-store (or inherits a no-cache default) makes the browser refetch on every render. That is one header away from being gone, and no server-side machinery is needed.

Fix ladder

Apply in order; each step is independently useful, and stopping early is fine when the signal disappears.

1. Cache headers. Per-user content: private, max-age=<ttl>. Content identical for every caller (icons, config, geocoding): public, max-age=<ttl>, immutable if the URL is content-addressed. Pick the TTL from the content's real update cadence — a marker icon changes on upload, so minutes-to-hours, not a year.

2. In-flight dedupe. Collapse concurrent identical misses into one upstream call:

const inflight = new Map<string, Promise<string>>()

async function fetchOnce(key: string): Promise<string> {
  const pending = inflight.get(key)
  if (pending) return pending

  const request = (async () => {
    try {
      const res = await upstream(key)
      if (!res.ok) throw new Error(`upstream ${res.status}`)
      const body = await res.text()
      cache.set(key, body)
      return body
    } finally {
      inflight.delete(key)   // delete in finally, never after resolve only
    }
  })()

  inflight.set(key, request)
  return request
}

3. Bounded TTL cache. Size-capped, oldest-evicted, rejecting expired entries on read. Cache the success path only — a cached failure turns one upstream hiccup into a TTL-long outage.

4. Batch. When one view needs many keys, a single endpoint that accepts a list beats N calls that are each cached well. Only worth it if the client can be changed too.

Invariants

  • Authorization and input validation run before the cache, so a cache hit can never serve content the caller is not allowed to see.
  • Cache key = exact upstream URL plus every input that changes the response (accept header, format, viewport). A key that drops an input serves the wrong variant.
  • Bound the map. An unbounded Map keyed by user-supplied URLs is a memory-exhaustion primitive — cap entries and evict.
  • Never let a client-supplied URL reach the cache without the same allowlist check the route already enforces; a cache is not a bypass.

Verification

Write the three tests before the code — concurrent collapse (one upstream call for two simultaneous requests), cached repeat (second request makes no upstream call), failure not cached (a failed upstream retries on the next request). Then confirm on the live route:

curl -sI "<route-url>" | grep -i cache-control

and count the upstream requests for a single page render in the network panel: the number should equal the number of distinct keys, once.

Reporting

State the before/after call count per render and the TTL chosen with its reason. "Added a cache" hides whether the burst or the repeat was fixed, and whether the TTL fits the content.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.