Skip to main content
KUSHAL SRINIVAS OP-2026
[ENGINEERING RECORD · SERVERLESS PERFORMANCE]

Everything Blog — Serverless Cost Audit & Edge Cache Policy

TanStack StartReact 19Vite / NitroVercelTypeScriptPostgreSQLVitest

Everything Blog is an AI-assisted news platform built with TanStack Start and deployed on Vercel. On a warm instance it felt fast. The bill was rising anyway, because too many requests reached the function at all.

The audit question was not “why is this code slow?” It was “which request-triggered paths run that should never run?” That framing found six paths. The biggest one was reader-facing HTML with no shared-cache TTL: the CDN was being told, in the response header, not to cache the page.

52 → 35
Cold upstream calls
−33% · stubbed-upstream benchmark
52 → 0
Warm repeat calls
1,439 ms → 2 ms repeat wall time
21 → 7
Search hydration calls
−67% in the audited optimization set
52
Tests passing
5 new cache-policy cases

Executive Summary

I ran a production audit, built a reproducible cold/warm benchmark, traced every request-triggered path, and implemented a privacy-aware caching and request-reduction layer. The work combined production cache-header probes, a stubbed-upstream benchmark, code tracing across loaders, server functions, upstream calls and database writes, unit tests, and a local production build.

The main cost was not slow code. It was work that should never have run: uncached HTML, per-hover loader invocations, search requests that hydrated twenty articles at once, analytics flushes that amplified into N+1 database writes, and repeated category and sitemap lookups.

I implemented a session-aware CDN cache policy, search request deduplication, cache-safe navigation staleness, and a removal of a broken load-more path. The change set was rebased onto a main branch that had advanced 48 commits, preserving only the production-safe subset. The evidence is 52 passing tests, a successful production build, and cache headers verified with curl against a local production server.

What the Audit Found

6 request-triggered cost paths
#Root causeEvidence
1Reader HTML had no shared-cache TTLProduction / was 1.59 s TTFB with cache-control: public, max-age=0, x-vercel-cache: MISS; same for /category, /about and /search
2Intent preloading multiplied loader invocationsdefaultPreload: 'intent' with zero stale time meant hover resolved a route and click resolved it again
3Search over-fetchedOne search = 1 search request + 20 article-detail requests = 21 upstream calls, plus a 300 ms debounce and a load-more path that re-fetched the same 20 results
4Analytics write amplification5 s flush loop + one INSERT per event = 6 queries for 5 events; the unload beacon posted to /__analytics and returned 404
5Duplicate data fetchesCategory lookups repeated inside category and article renders; the sitemap walked 20 pages and then fetched a separate categories page
6Unbounded upstream latencyThe baseline fetch() had no abort timeout, so a hung API could run to the platform limit

The sitemap and RSS feeds were already CDN-cached (HIT, age 2572/2571), so the primary driver was reader HTML, not those feeds. A page that returns max-age=0 is a page that asks the CDN to send every view to the function. Once HTML is uncached, every reader view, crawler hit and hover-preload becomes a billable invocation. The other five findings multiply that base.

What Shipped in the Production-Safe Branch

Changes in perf/edge-cache-search
ChangeMechanismWhy
Session-aware cache policysrc/lib/cache-policy.ts + src/start.tsAnonymous HTML can share a CDN copy; signed-in HTML must not
Category, static and search cachings-maxage=60 for feed, article and category; 86,400 for static; 300 for the search shellTurns repeat views and crawler hits into cache hits with no invocation
Query-variant safety?q= search pages bypass the cacheAvoids serving one serialized search state across variants
Cache-safe navigationdefaultStaleTime: 30,000Back/forward and rapid navigation reuse loader data
Search request reduction500 ms debounce, 2-character typing threshold, per-term cache, request-id guardFewer server-function invocations while typing; stale responses dropped
Duplicate path removedRemoved the broken load-more results buttonThe search API has no pagination; it appended the same 20 results
Tests5 cache-policy casesLocks in public/private behaviour

The policy is deliberately conservative. Anonymous pages get a time-bounded CDN copy; signed-in pages are never shared. The below is the landed logic:

if (!isPublicPage) return null;
if (hasSession) return "private, no-store";
if (isStatic) return "public, max-age=0, s-maxage=86400, stale-while-revalidate=604800";
if (isSearchShell) return "public, max-age=0, s-maxage=300, stale-while-revalidate=3600";
return "public, max-age=0, s-maxage=60, stale-while-revalidate=300";

The session check is a privacy rule before it is a cost rule. A cached page that leaks a username is worse than a slow page.

What the Benchmark Measured

The benchmark uses a stubbed upstream at 40 ms latency with 1,200 articles, and compares a cold request with an immediate repeat. It runs on the audited baseline, not against post-deployment Vercel metrics.

Upstream calls per scenario (40 ms stubbed upstream, 1,200 articles)
ScenarioCold beforeCold afterRepeat beforeRepeat after
Home2220
Category3230
Article3230
Sitemap2120210
Search217210
Pagination2220
Total5235 (−33%)520 (2 ms)

Cold wall time moved from 1,439 ms to 1,359 ms; the remaining time is the sequential sitemap walk, which is now edge-cached. Repeat wall time moved from 1,439 ms to 2 ms. Search wall time moved from 147 ms to 104 ms (−29%).

Analytics write amplification
BatchBeforeAfter
1 event2 queries2
5 events6 queries2
20 events21 queries2
50 events51 queries2

The batching fix is the clearest structural win: the query count becomes constant instead of growing with the event count. It also removes a write storm from the path that runs when a reader leaves the page.

Verified Cache Headers

Landed policy, verified with curl against a local production server
RouteCache-Control
/category/technologypublic, max-age=0, s-maxage=60, stale-while-revalidate=300
/aboutpublic, max-age=0, s-maxage=86400, stale-while-revalidate=604800
/editorialpublic, max-age=0, s-maxage=86400, stale-while-revalidate=604800
/privacypublic, max-age=0, s-maxage=86400, stale-while-revalidate=604800
/searchpublic, max-age=0, s-maxage=300, stale-while-revalidate=3600
/search?q=techno Cache-Control; X-Robots-Tag: noindex, follow
/adminprivate, no-store
/ + Cookie: eb_sess=…private, no-store
/category/… + Cookieprivate, no-store

Trade-offs

Every caching decision is a staleness decision
DecisionTrade-off
Anonymous-only HTML cachingSigned-in readers always hit the function
60 s feed/category TTLUp to 60 s stale
1 day static TTLDeploy purge needed if the page is edited
300 s search shellOnly the bare /search path is cached
30 s navigation stale timeA route can show 30 s-old loader data
500 ms search debounceSlightly slower perceived search
Remove search load-moreOnly the first 20 matches are shown
Rebase instead of force-pushHad to re-evaluate which changes were still valid

Verification

  • pnpm test → 52 passing, including 5 new cache-policy cases.
  • pnpm build → success.
  • tsc --noEmit → no errors in the changed files.
  • Local production server + curl → headers in the table above.
  • No force-push. Remote main had advanced 48 commits, so the safe subset was rebased.

Remaining Bottlenecks

  • Search hydration. Still one search request plus up to twenty article requests. The upstream search API needs summary fields so the list can render without a detail call per result.
  • Shared cache. The web layer relies on API Redis and the CDN. A shared cache across isolates would help, but it must be keyed by API key.
  • Sitemap pre-generation. The current walk is budgeted at 6.5 s and edge-cached for one hour. A scheduled Blob/KV job would remove the tail.
  • Developer pages. API-backed loaders are intentionally not blanket-cached.
  • Analytics volume. Already batched and rate-limited; sampling or bot filtering is the next step if needed.

Source: internal performance report docs/perf/PORTFOLIO-REPORT.md · commit 2818057 · branch perf/edge-cache-search.

Final Takeaway

The useful finding was not a slow function. It was a cache header that told the CDN not to cache, a preload that resolved the same route twice, a search that fetched twenty details to render twenty links, and an analytics flush that turned five events into six queries. None of those is a code-speed problem. All of them are request-elimination problems.

On serverless, the fastest invocation is the one that never happens. Measure the request paths before optimising the request handler.

Read next: the NewsTok architecture record and the performance ledger.

BACK TO ALL ENTRIES