Skip to content

perf(api): tune caching, retries, and prefetch pressure - #118

Merged
Ardnived merged 5 commits into
mainfrom
perf/api-tuning
Aug 7, 2026
Merged

Ardnived merged 5 commits into
mainfrom
perf/api-tuning

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Closes #97

What this does

React Query's architecture in this repo was already good (fetch-once, stale-while-revalidate, warm-up on boot, quantized keys) — its pressure knobs were untouched defaults. This tunes all four, in the query-configuration layer.

1. staleTime — a list remount now recomputes nothing

eventsQuery issues no request: it re-derives the list from the already-cached feed (full-feed predicate + a zod parse per surviving event + a distance sort). With React Query's default staleTime: 0, every drawer remount redid all of it against bytes that could not have changed.

EVENTS_STALE_TIME is deliberately the same number as GEOJSON_STALE_TIME rather than an independently chosen one — a derived query can be no fresher than its only input. A 30 s DEFAULT_STALE_TIME floor sits under everything else, which also stops the hover prefetch being paid for and immediately thrown away by the view's own mount.

2. Retry — bounded, jittered, 4xx-aware

The default 3× retry meant every embedded client quadrupled its load against SahajCloud during precisely the outage that made the first request fail. Now 1 retry, a backoff capped at 4 s and jittered (so a recovering API isn't met with every client's second attempt in the same millisecond), and never for a 4xx — including 429, where retrying is the one response that makes things worse. 408/425 are excepted: they describe a moment, not a verdict. Mutations stay at retry: 0 — the one mutation is a registration, and an auto-resend is a duplicate signup.

3. Hover prefetch — dwell + a shared concurrency cap

Dragging the cursor down the results list fired one GET /events/:id per row crossed (distinct keys, so dedup couldn't help). Two independent bounds, since either alone leaks: a 150 ms dwell (a sweep clears a row in ~10–30 ms; a deliberate hover before a click runs 300–800 ms) and a shared cap of 2 in flight, dropped rather than queued. The gate is a pure closure in lib/ so the node lane drives it with fake timers.

4. gcTime — the wholesale caches survive an idle gap

The 5-minute default is shorter than REGIONS_STALE_TIME, so the region tree could be evicted while still nominally fresh and "fetched once per session" quietly became "fetched once per idle gap". Worst where least visible: a map=false embed holds no observer on the feed at all. ['regions'] / ['geojson'] / ['event-titles'] are pinned to an hour. The loaders stay on ensureQueryData({ revalidateIfStale: true }) — not switched to fetchQuery.

Two bugs the reviews caught, both worth reading

A per-fetch retry: false does not stay on the fetch that asked for it. I had put retry: false on the speculative warm. Verified in query-core 5.62.16: prefetchQuery → fetchQuery → query.fetch(opts) writes those options onto the shared Query object, and useSuspenseQuery reaches it through fetchOptimistic, which calls query.fetch() with no arguments and inherits whatever the last writer left. So hovering a card disabled retries for EventView's own read of it — every event anyone ever pointed at, and a regression against main. Removed; shouldRetryQuery already caps at one attempt and skips 4xx.

Giving the client a retry default silently un-defaulted the imperative reads. fetchQuery applies retry: false for free while retry is undefined — a client default kills that guard. The three ensureQueryData loaders are awaited from inside queries that retry, so a retry there multiplies: a failing region open would make four requests for the feed where MAX_QUERY_RETRIES promised two. They now pin retry: false explicitly (safe: nothing reads those keys with suspense).

Values chosen

Knob Value Why
DEFAULT_STALE_TIME 30 s Inside "the same interaction", outside "this might have changed"
EVENTS_STALE_TIME = GEOJSON_STALE_TIME (5 min) A derived query can be no fresher than its input
EVENTS_GC_TIME 2× its stale window Floor is gc ≥ stale; the extra buys a stale repaint instead of a suspense spinner
WHOLESALE_GC_TIME 1 h Outlives any idle gap in one page view; bounded entry count
MAX_QUERY_RETRIES 1 The error boundary already offers a manual "Try again"
MAX_RETRY_DELAY 4 s vs. React Query's 30 s
HOVER_DWELL_MS 150 Sits in the gap between a sweep (10–30 ms) and a hover-to-click (300–800 ms)
MAX_CONCURRENT_PREFETCH 2 Covers "moved on while the first is loading"; a viewer can only open one event

Verification

lint · typecheck · test:run (690 pass, 25 new) · build (incl. the CSS-scope assertion) · size (482.2 / 483.7 KiB against 495 KiB — unchanged by this branch).

The three new specs prove the claims rather than restating the constants:

  • api/query-pressure.test.ts drives a real QueryObserver through mount → unmount → remount with a counted query fn: 1 call across three mounts, and a staleTime: 0 control that gets 3, so the test fails if the staleTime is ever dropped. Also asserts the factories carry their gcTime — a pin that's defined but never wired reads exactly like one that is.
  • config/query-client.test.ts covers the retry predicate (boundary, every 4xx, the 408/425 exceptions, our own tagged kinds, hostile non-Error values) and the jittered capped delay, then asserts the shared client actually carries the policy — without that, the whole defaultOptions block could be deleted with every other assertion still green.
  • lib/prefetch-intent.test.ts sweeps 40 rows at 20 ms each and asserts zero warms, then that resting on one row warms exactly once, plus the cap, budget return, and same-row re-entry.

Manual check worth doing: hover a results card and confirm the detail still opens instantly (the dwell is ~150 ms, well under hover-to-click), and that sweeping the list fires no /events/:id in the network panel. Browser verification wasn't run on this branch — a sibling agent held the shared browser.

Deliberately not changed

  • No geojsonQuery() factory. Six call sites hand-roll ['geojson'] inline; the pin is applied at the loader (query-core max-merges gcTime, and warmCaches creates the entry first). Recorded as follow-up — this change is what makes the missing factory load-bearing rather than untidy.
  • regionsQuery not moved into fetch.ts to collapse its duplicate declaration — that restructures a loader the ticket puts out of scope. Both sites now cross-reference each other.
  • Retryability not unified with ERROR_POLICY. shouldRetryQuery's kind list mirrors that table's retry column; the proper fix is a shared RETRYABLE_KINDS in lib/report.ts, which edits a molecule a sibling branch may hold. Both sides now name the other.
  • The list is still unvirtualized and the feed still wholesale — §1.2/§1.3 of the readiness report, separate work.

Out-of-scope edits, and why

Two files outside the ticket's owned set, both one-statement additions closing a gap this branch opens:

  • Widget.tsx — queryClient.clear() beside the existing atlasAuth.apiKey = null on teardown. Only ['client', apiKey] keys on the credential; the wholesale caches don't, and this branch takes their guaranteed retention from 5 min to an hour, so a re-add under a different api-key would read the first key's responses. The teardown already handles exactly this concern for the key itself.
  • PreviewController.tsx — a comment that said "the global staleTime of 0", which this branch made false.

Reviews

/simplify (4 angles) · one /code-review pass · security-review (required — the diff touches src/config/api/). Security found nothing critical or high; its one medium is the Widget.tsx cache-release above, now fixed.

Dismissed, with reasons: halving EVENTS_GC_TIME to 1× (would trade a stale repaint for a suspense spinner on a remount just past the window); dropping the delay option from createPrefetchIntent (the options bag exists for maxInFlight regardless, and hard-coding the primary parameter of a dwell helper is the asymmetric choice).

Commits are unsigned — the 1Password SSH agent had no identities loaded this session.

🤖 Generated with Claude Code

Ardnived and others added 5 commits August 6, 2026 21:38
React Query's untouched defaults were the wrong shape for a widget embedded on
pages we don't own:

- staleTime 0 meant every remount of the results list re-ran the full-feed
  predicate, a zod parse per surviving event and a distance sort against bytes
  that could not have changed. The derived query is now fresh for exactly as
  long as the feed it derives FROM, with a 30s floor under everything else so
  the hover prefetch isn't immediately thrown away by the view's own mount.
- retry 3x meant every client quadrupled its load against SahajCloud during
  precisely the outage that made the first request fail. Now one retry, a
  jittered capped backoff (so a recovering API isn't met with a synchronized
  second wave), and never for a 4xx — which includes a 429, where retrying is
  the one response that makes things worse. Mutations stay at 0: an automatic
  re-send of a registration is a duplicate signup.
- gcTime 5min could evict the wholesale caches the fetch-once architecture
  depends on. Worst where least visible: a map=false embed holds no observer on
  the feed at all. Pinned to an hour, and the specs assert the real invariant --
  gcTime above staleTime, or the stale window is unobservable.

The loaders stay on ensureQueryData({ revalidateIfStale: true }); the gcTime is
strictly additive.

Refs #97

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Warming an event's detail on mouseenter is free when the pointer is arriving at
a card and pure waste when it is merely passing over one. The results list pages
to hundreds of rows, so dragging the cursor down it fired one GET /events/:id
per row crossed -- distinct keys, so React Query's dedup could not help -- and
the widget runs on host pages at whatever traffic those pages have.

Two independent bounds, since either alone leaks. A 150ms dwell sits in the wide
gap between sweeping a row (~10-30ms) and hovering one before a click
(300-800ms), so a sweep fires nothing while a real hover still leaves most of
its travel time for the request. A shared cap of 2 outstanding warms stops
patient hovering from becoming the same storm in slow motion; over the cap a
warm is dropped rather than queued, because a queue just delivers the burst late
and the card actually opened fetches through its own suspense read anyway.

The gate is a pure closure in lib/ so the node lane drives it with fake timers
rather than asserting timing through a rendered list. It is module-scoped on
purpose: a per-card instance would hand every row its own budget, which is no
budget at all. The card's unmount teardown is keyed for the same reason -- rows
unmount constantly as the list re-pages, and a bare dispose() would let a
neighbour cancel the warm for the row under the cursor.

The touch-device idle warm-up stays ungated (already bounded to 3, and metering
it would starve the one device with no hover to fall back on), and a speculative
warm opts out of retries entirely.

Closes #97

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- shouldRetryQuery is guarded like classifyError is: it runs inside the retryer
  on whatever a third party rejected with, and the raw `status` read it added was
  the one thing there that could throw. Its comments now say why that read exists
  (the classifier deliberately maps only some statuses) and name ERROR_POLICY's
  retry column as the co-owner of the kind list, with the unification recorded.
- Dropped the release latch in the prefetch gate: exactly one path runs and a
  settled promise calls back once, so the latch guarded nothing and taught a
  phantom failure mode. `fire` now reuses `cancel()` instead of re-nulling.
- useHoverPrefetch lost a useRef + useEffect + useMemo. They ran on every row of
  the repo's one memoized 1000-row list to cancel at most ONE pending warm --
  the gate holds a single timer -- and every case where the pointer actually
  leaves is already covered by `leave`.
- usePrefetchEvent is module-private now; the two hooks are the ways in.
- The spec reuses the shared `sdkError` fixture rather than re-declaring the SDK
  error shape, and the invariant block says it is a tripwire on the definitions.
- Cross-referenced the two declarations of the ['regions'] contract.

Refs #97

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…uery

/code-review found the retry override did not stay on the prefetch. Verified in
query-core 5.62.16: prefetchQuery -> fetchQuery -> query.fetch(opts) writes those
options onto the shared Query object, and useSuspenseQuery reaches it through
fetchOptimistic, which calls query.fetch() with NO arguments and so inherits
whatever the last writer left. So hovering a card disabled retries for EventView's
own read of it -- i.e. for every event anyone ever pointed at, and a regression
against main. A per-fetch retry override is not expressible through a shared key;
shouldRetryQuery already caps at one attempt and skips 4xx, which is all a
speculative warm needed.

The same review found the opposite problem one layer down. fetchQuery applied
`retry: false` for free while `retry` was undefined; giving the client a default
killed that guard, and the three ensureQueryData loaders are awaited from INSIDE
queries that retry -- so a failing region open would make four requests for the
feed where MAX_QUERY_RETRIES promised two. They now pin it explicitly.

Also from the two reviews:

- Widget teardown clears the query cache beside the api-key release. Only
  ['client', apiKey] keys on the credential; the wholesale caches do not, and this
  branch took their guaranteed retention from 5 minutes to an hour, so a re-add
  under a different key would read the first key's responses.
- Hover warming is skipped while navigator says we're offline: networkMode
  'online' PAUSES such a fetch, so its promise never settles and two of them would
  strand the in-flight budget for the session.
- 408 and 425 are excepted from the 4xx no-retry rule -- they describe a moment,
  not a verdict.
- `enter` for the row already dwelling is a no-op, so a card firing both
  mouseenter and focus can't push its own warm past the click.
- The in-flight counter is floored: an extra release would RAISE the cap.
- The specs now assert the WIRING (the client's default options, the factories'
  gcTime), not just the exported helpers -- the whole defaultOptions block could
  be deleted with every previous assertion still green.

Refs #97

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The rule described the caching architecture but not the numbers it depends on,
which is how all four defaults stayed untouched. Adds a "Pressure knobs" section
covering the stale floor and why the events window IS the feed's window, the
gcTime-must-exceed-staleTime invariant (and why a map=false embed is the worst
case), the bounded 4xx-aware retry and its mirror in ERROR_POLICY, and the hover
gate.

Two facts worth having written down before someone rediscovers them:

- Never override an option per-fetch on a SHARED key. fetchQuery writes options
  onto the shared Query object and fetchOptimistic reads them back with no
  arguments, so a `retry: false` meant for a prefetch lands on the suspense read.
- The imperative loaders pin `retry: false` because they are awaited from inside
  queries that retry, not because a retry there would be wrong in isolation.

Also renames the hover-prefetch hook to `useHoverPrefetch` in the prose.

Refs #97

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying sahajatlas-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: f4a3075
Status: ✅  Deploy successful!
Preview URL: https://e6a584b5.sahajatlas-design.pages.dev
Branch Preview URL: https://perf-api-tuning.sahajatlas-design.pages.dev

View logs

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: f4a3075
Status: ✅  Deploy successful!
Preview URL: https://9d0d5e0b.sahajatlas.pages.dev
Branch Preview URL: https://perf-api-tuning.sahajatlas.pages.dev

View logs

@Ardnived
Ardnived merged commit e1f3b64 into main Aug 7, 2026
5 checks passed
@Ardnived
Ardnived deleted the perf/api-tuning branch August 7, 2026 16:19
Ardnived added a commit that referenced this pull request Aug 7, 2026
One conflict, in README.md's CSP block, and it was load-bearing: this
branch added `https://cdn.usefathom.com` to script-src plus a warning
that CSP ignores every repeat of a directive name after the first, while
#121 added the widget's own origin as a SECOND `script-src` line — the
exact mistake the warning describes. Merged onto one line carrying all
three sources, so a host pasting the block actually gets Turnstile and
Fathom rather than silently losing them, and kept both explanations.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.

perf(api): tune caching, retries, and prefetch pressure

1 participant