Repository navigation
worker: stale-while-revalidate so cache hits never wait on the GitHub fanout - #445
Conversation
… fanout The /activity stat strip took a couple of seconds to load on every visit that landed inside a fresh 5-minute window: the first request fanned out 12 concurrent GitHub Search calls and the viewer waited for them. Now serveCached always returns from the colo cache immediately; when the cached entry is past its freshness budget, the hit also kicks off a ctx.waitUntil(refreshAndCache) so the next viewer gets fresher data. Only a cold cache — a fresh deploy, or a quiet stretch longer than ten freshness budgets — makes one request synchronously refresh. Each cached response carries x-tend-stale-at (epoch ms) and Cache-Control with s-maxage = STALE_SERVE_FACTOR * ttl, so the colo cache retains the entry far past its freshness budget — that's what makes SWR keep working between viewers. Browsers ignore s-maxage and use max-age. A missing or garbled stamp counts as stale, so the first hit self-heals an entry written by the old code. Verified against the live deploy that Cloudflare's zone CDN isn't caching this Worker route (no cf-cache-status / Age headers), so s-maxage only affects caches.default retention as designed. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
tend-agent
left a comment
There was a problem hiding this comment.
worker/README.md still describes the pre-SWR model — "How it works" calls the rendered response "edge-cached (caches.default) for 30 s" and credits the edge with deduping concurrent misses; the "Cache strategy" section says the colo TTL is Cache-Control: max-age; line 32 quotes the Cache-Control as public, max-age=30; lines 5–6 say "edge TTL". Worth bringing in line with the docs/website-data.md rewrite and the updated source comments. Happy to push a follow-up commit if useful.
Otherwise reads cleanly — the stamp-based SWR with s-maxage for colo retention is the simplest shape that works around CF's lack of native stale-while-revalidate, the cold-cache vs stale-hit split is clean, and the STALE_AT_HEADER-counts-as-stale fallback self-heals entries written by the old code.
The Cache-Control example, "How it works", and "Cache strategy" sections still described the pre-SWR model (30s edge TTL, edge-dedupes-misses, Cache-Control: max-age=30). Rewrite to the current shape: stale-while-revalidate from the colo cache, max-age + s-maxage split, x-tend-stale-at stamp, per-route fanout shapes for both endpoints. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…s per stale window (#449) PR #445 (stale-while-revalidate) called out an open trade-off: a burst of concurrent stale-hits could each fan out their own background refresh, so K viewers landing on a stale `/activity` entry triggered K Search fanouts — 4·N·K Search calls against GitHub's 30/min cap. The short fallback budget capped the fallout but the burst was wasteful. This coalesces the burst. Before firing the real refresh in the stale-hit branch, the worker pushes the cached entry's `x-tend-stale-at` forward by `REFRESH_GRACE_MS` (30 s) and writes it back to the colo cache; concurrent stale-hits arriving within that window read the bumped entry as `isStale → false` and skip starting their own refresh. The real refresh's put overwrites the bumped entry with fresh data when it completes. One refresh per stale window per colo, instead of one per viewer. ### Mechanism `coalesceAndRefresh` (new) sequences two puts: a bump-put that copies the cached body and overrides only `x-tend-stale-at`, then a fresh-put with the refresh result (or fallback payload on throw — fallback budget semantics preserved, since the bump only extends staleness up to the moment the real put lands). `refreshAndCache` (cold path) is unchanged in behavior; the refresh-or-fallback logic is extracted into `freshResponse` and shared. ### Trade-offs left in Not perfectly one refresh per stale window. K viewers reading the stale entry within the colo's cache-propagation window (a few ms in practice) all still enter `coalesceAndRefresh` and fire a refresh — once a bump-put propagates colo-wide, subsequent viewers skip. So K drops from "all viewers in the stale window" to "viewers in the propagation window", a meaningful improvement without needing Durable Objects. Decision-time jitter (xfetch) would tighten this further; deferred until traffic actually surfaces it. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…459) ## Summary In the recent-activity feed, `review` and `comment` rows used to link to the parent PR/issue — a bot review on a long thread would drop the viewer at the top, not on the actual approval/comment. This resolves the deep URL per row. - `RecentItem.url` for the `reviews` bucket now resolves to the bot's most recent review (`…#pullrequestreview-<id>`). - `RecentItem.url` for the `comments` bucket now resolves to the bot's most recent issue/PR-conversation comment (`…#issuecomment-<id>`). - `prs` and `issues` rows are unchanged — those *are* the things tend created. ## How After each Search query returns the recent N items, the Worker issues one extra REST call per recent item (`/pulls/{n}/reviews` for `reviews`, `/issues/{n}/comments` for `comments`), picks the latest entry authored by the originating bot, and uses its `html_url`. Failures (404, no bot match, transient error) silently fall back to the parent's `html_url` so a broken follow-up never drops a row. With `RECENT_PER_BUCKET = 10`, that's up to 20 extra REST calls per refresh — under the 5,000/hr cap, and with SWR landed on #445 they run in the background `waitUntil` refresh, never on viewer time. The bot is tracked per item during the Search-merge step (each item carries its `bot` through `Array<SearchItem & { bot: string }>`) so the follow-up looks for the right author. ## Test plan - [x] `cd worker && npm test` (19 tests, including new success + fallback paths) - [x] `cd worker && npm run typecheck` - [x] `cd site && npx astro build` - [x] `pre-commit run --all-files` --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
The
/activitystat strip —964 PRs / 1,512 comments / 186 issues— took a couple of seconds to load on every visit that landed inside a fresh 5-minute window: the first request fanned out 12 concurrent GitHub Search calls and the viewer waited for them.This is stale-while-revalidate. A request always returns from the colo cache immediately; when the cached entry is past its freshness budget, the hit also kicks off a
ctx.waitUntil(refreshAndCache(...))so the next viewer gets fresher data. Only a cold cache — a fresh deploy, or a quiet stretch longer than ten freshness budgets — makes one request synchronously refresh.Mechanism
Each cached response carries
x-tend-stale-at(epoch ms = put time + ttl) andCache-Control: public, max-age=<ttl>, s-maxage=<10·ttl>. The colo cache honorss-maxage, keeping the entry serveable for 10 budgets (5 min on/currently-tending, 50 min on/activity). Browsers ignores-maxageand usemax-age.serveCachedreads the stamp on each hit to decide whether to background-refresh; a missing or garbled stamp counts as stale, so the first hit after this deploys self-heals any entry written by the old code.Fallback budget semantics are preserved: a refresh that throws still writes the empty payload with
opts.ttl.fallback, so the next visitor retries quickly.Verified
curl -sD- https://api.tend-src.com/activityagainst the current production deploy returns nocf-cache-statusand noAgeheader, confirming Cloudflare's zone CDN isn't caching this Worker route — sos-maxageonly affectscaches.defaultretention, exactly as the design assumes. A note next to theCache-Controlline flags the assumption so a future Cache Rule on this host would prompt a revisit.Tests, typecheck, and
pre-commitall green; added 2 unit cases for the pureisStalehelper (boundary, missing, garbled stamps).Trade-offs left in
A burst of concurrent stale-hits can fan out several refreshes at once; the short fallback budget caps the damage if that ever trips a rate limit.
STALE_SERVE_FACTOR = 10is one knob across both routes; per-route values would be straightforward but add a knob without a current pain point. A cron prewarm would close the cold-start gap entirely but trade away the "zero GitHub calls when idle" property — documented as a deliberate non-choice indocs/website-data.md.🤖 Generated with Claude Code