Repository navigation
perf(api): tune caching, retries, and prefetch pressure - #118
Merged
Merged
Conversation
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]>
Deploying sahajatlas-design with
|
| 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 |
Deploying sahajatlas with
|
| Latest commit: |
f4a3075
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://9d0d5e0b.sahajatlas.pages.dev |
| Branch Preview URL: | https://perf-api-tuning.sahajatlas.pages.dev |
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 nothingeventsQueryissues 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 defaultstaleTime: 0, every drawer remount redid all of it against bytes that could not have changed.EVENTS_STALE_TIMEis deliberately the same number asGEOJSON_STALE_TIMErather than an independently chosen one — a derived query can be no fresher than its only input. A 30 sDEFAULT_STALE_TIMEfloor 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/:idper 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 inlib/so the node lane drives it with fake timers.4.
gcTime— the wholesale caches survive an idle gapThe 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: amap=falseembed holds no observer on the feed at all.['regions']/['geojson']/['event-titles']are pinned to an hour. The loaders stay onensureQueryData({ revalidateIfStale: true })— not switched tofetchQuery.Two bugs the reviews caught, both worth reading
A per-fetch
retry: falsedoes not stay on the fetch that asked for it. I had putretry: falseon the speculative warm. Verified in query-core 5.62.16:prefetchQuery→fetchQuery→query.fetch(opts)writes those options onto the sharedQueryobject, anduseSuspenseQueryreaches it throughfetchOptimistic, which callsquery.fetch()with no arguments and inherits whatever the last writer left. So hovering a card disabled retries forEventView's own read of it — every event anyone ever pointed at, and a regression againstmain. Removed;shouldRetryQueryalready caps at one attempt and skips 4xx.Giving the client a
retrydefault silently un-defaulted the imperative reads.fetchQueryappliesretry: falsefor free whileretryisundefined— a client default kills that guard. The threeensureQueryDataloaders are awaited from inside queries that retry, so a retry there multiplies: a failing region open would make four requests for the feed whereMAX_QUERY_RETRIESpromised two. They now pinretry: falseexplicitly (safe: nothing reads those keys with suspense).Values chosen
DEFAULT_STALE_TIMEEVENTS_STALE_TIMEGEOJSON_STALE_TIME(5 min)EVENTS_GC_TIMEWHOLESALE_GC_TIMEMAX_QUERY_RETRIESMAX_RETRY_DELAYHOVER_DWELL_MSMAX_CONCURRENT_PREFETCHVerification
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.tsdrives a realQueryObserverthrough mount → unmount → remount with a counted query fn: 1 call across three mounts, and astaleTime: 0control that gets 3, so the test fails if thestaleTimeis ever dropped. Also asserts the factories carry theirgcTime— a pin that's defined but never wired reads exactly like one that is.config/query-client.test.tscovers 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 wholedefaultOptionsblock could be deleted with every other assertion still green.lib/prefetch-intent.test.tssweeps 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/:idin the network panel. Browser verification wasn't run on this branch — a sibling agent held the shared browser.Deliberately not changed
geojsonQuery()factory. Six call sites hand-roll['geojson']inline; the pin is applied at the loader (query-core max-mergesgcTime, andwarmCachescreates the entry first). Recorded as follow-up — this change is what makes the missing factory load-bearing rather than untidy.regionsQuerynot moved intofetch.tsto collapse its duplicate declaration — that restructures a loader the ticket puts out of scope. Both sites now cross-reference each other.ERROR_POLICY.shouldRetryQuery's kind list mirrors that table'sretrycolumn; the proper fix is a sharedRETRYABLE_KINDSinlib/report.ts, which edits a molecule a sibling branch may hold. Both sides now name the other.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 existingatlasAuth.apiKey = nullon 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 differentapi-keywould 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-reviewpass ·security-review(required — the diff touchessrc/config/api/). Security found nothing critical or high; its one medium is theWidget.tsxcache-release above, now fixed.Dismissed, with reasons: halving
EVENTS_GC_TIMEto 1× (would trade a stale repaint for a suspense spinner on a remount just past the window); dropping thedelayoption fromcreatePrefetchIntent(the options bag exists formaxInFlightregardless, 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