Skip to content

Remove Front Door route cache and make /healthz no-store - #1937

Merged
David Pine (IEvangelist) merged 3 commits into
mainfrom
ievangelist-afd-use-query-string-caching
Oct 22, 2026
Merged

David Pine (IEvangelist) merged 3 commits into
mainfrom
ievangelist-afd-use-query-string-caching

Conversation

@IEvangelist

@IEvangelist David Pine (IEvangelist) commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Removes the Front Door route cache (route.CacheConfiguration) so every request reaches StaticHost, following Eric's review comment. This replaces the earlier UseQueryString change in this PR.

Why: Front Door caches StaticHost's 301 redirects, which carry no Cache-Control, for 1-3 days. A stale Location or a replayed query string then sticks until someone purges the endpoint. The origin already sets no-cache on pages and immutable on /_astro/*, and serves brotli, so the edge cache adds little.

Also in this PR: /healthz returns Cache-Control: no-store, so a health probe is never answered from a stored copy.

Trade-offs, none measured yet on a deployed Front Door:

  • /_astro/* is no longer cached at the edge.
  • Front Door compression lived in the cache configuration and goes away. StaticHost serves only precompressed brotli, so clients that accept gzip but not brotli get uncompressed content.
  • Front Door doesn't support ETag. With no cache, conditional requests should reach StaticHost and return 304, but this is untested.
  • It's untested whether redirects already cached at the edge keep being served. Purge the endpoint if any do.

If measurements justify it, a second route that caches only /_astro/* can restore edge caching for fingerprinted assets.

The generated bicep on the internal deploy branch is refreshed in the follow-up internal PR.

Third-party links and affiliations

None

Validation

  • dotnet test tests\StaticHost.Tests\StaticHost.Tests.csproj --filter "FullyQualifiedName!~Live.Redis" --nologo -v q: passed, 332 tests. The Redis integration tests need Docker and were excluded.
  • Ran StaticHost locally: GET /healthz returned 200 with Cache-Control: no-store, and GET / kept no-cache and its ETag.
  • aspire publish on a throwaway worktree of the internal deploy branch with an earlier revision of these changes: the Front Door route lost cacheConfiguration. The only other drift was alwaysOn: true on the website bicep, which this PR no longer sets.
  • Not run: pnpm build. No frontend files changed.
  • After deploy (can't be checked before): the route has no cacheConfiguration; /healthz returns no-store (expect X-Cache: CONFIG_NOCACHE); slashless URLs redirect correctly on every edge; a conditional GET returns 304; assets are still brotli.

The Front Door route used IgnoreQueryString, so the first requester's query string was stored in StaticHost's cached slashless-directory 301 and replayed to every later visitor. Use UseQueryString so each query string is cached separately.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 90ef1a20-cd65-43f3-97cd-6fa484d8b0a4
Copilot AI balanced review requested due to automatic review settings October 21, 2026 13:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The focused change addresses the cache-key mismatch; deployment still requires the documented endpoint purge.

No open issues 🎉

What changed in this PR

Updates Front Door caching so slashless-directory redirects do not replay another visitor’s query string.

Changes:

  • Uses UseQueryString to cache responses separately by query string.
  • Adds a comment explaining why redirects require this behavior.
File Description
src/​apphost/​Aspire.Dev.AppHost/​Extensions/​DeploymentExtensions.cs Includes query strings in Front Door cache keys.

Review effort: Balanced

@eerhardt

Copy link
Copy Markdown
Member

Review discussion on whether the Front Door route cache is needed at all, in addition to the UseQueryString fix.

Background

  • QueryStringCachingBehavior controls whether the query string is part of the Front Door cache key.
    • IgnoreQueryString: /a?x=1 and /a?x=2 share one entry, and the first response is replayed to everyone until it expires.
    • UseQueryString: each distinct URL, including its query string, gets its own entry.
    • IgnoreSpecifiedQueryStrings / IncludeSpecifiedQueryStrings: the key uses all parameters except, or only, the listed ones.
  • The ARM/Bicep reference and the Front Door caching docs don't state a default, and Azure.Provisioning leaves the property unset unless assigned, so it's best set explicitly.
  • Setting route.CacheConfiguration turns on the Front Door edge cache for every GET through the route. Omitting it disables caching. This is not the Redis cache StaticHost uses for live status.
  • The block comes from the first public Bicep (8b1492be, "Initial public release") and was carried forward by Use Aspire Front Door integration #967 ("preserve the existing … caching configuration"). No rationale is recorded.
  • Front Door compression is configured inside the route's cache config and only works when caching is enabled.

What the live origin does today

Probed against live aspire.dev (Kestrel, not behind AFD, brotli already applied at the origin):

Response Cache-Control Under AFD "honor origin" (default)
HTML, .md, xml, txt, scripts/*.js no-cache + ETag Not cached
404 page no-cache, no-store, must-revalidate Not cached
Accept: text/markdown negotiated response private, max-age=0, must-revalidate Not cached
/_astro/* fingerprinted assets max-age=31536000, public, immutable Cached for a year (safe)
Favicons max-age=3600, must-revalidate Cached up to 1 hour
301/308 redirects (slashless dir, canonical case, http to https) none Cached for 1-3 days

Per the Front Door caching docs, with caching enabled Front Door honors origin directives (including no-cache, private, no-store) and only falls back to a 1-3 day cache duration when the origin sends none.

What happens when content changes

  • Pages stay fresh because the origin says no-cache.
  • Fingerprinted assets get new URLs on every deploy, so they can't go stale.
  • Redirects are the only real staleness risk. A changed or removed redirect, a bad Location, or the query-string replay this PR fixes can persist for days until the endpoint is purged (az afd endpoint purge). I found no purge step in the AppHost or .github/workflows.

What the route-wide cache buys us

  • Pages: nothing, since they are no-cache.
  • Compression: nothing needed. The origin already serves brotli and Front Door passes compressed responses through. Compressing on both sides can also cause 503s on range requests (documented in the compression article).
  • Assets: edge caching of /_astro/* is the only real gain (a latency hop and some origin load).

Suggestion

  1. For the cutover, remove route.CacheConfiguration. That matches today's behavior (no edge caching) and removes the purge dependency. It also makes the UseQueryString change unnecessary.
  2. If measurements later justify it, add a second route for /_astro/* with caching on and leave /* uncached.
  3. If we keep the route-wide cache, UseQueryString is the minimum fix. StaticHost's redirects should also get an explicit Cache-Control (no-cache or a short max-age), otherwise any future response without a header is cached for 1-3 days.

Not verified: this was not tested against a real Front Door profile, since Dev/Test aren't resolvable and none was provisioned. The "honors no-cache" behavior comes from the docs above. Origin headers were measured on the live site.

The route-wide Front Door cache stores redirects that carry no Cache-Control
for 1-3 days. A wrong or stale Location, or a replayed query string, then
sticks until someone purges the endpoint. The origin already sends no-cache
on pages and immutable on /_astro/*, and already serves brotli, so the cache
adds little. Drop route.CacheConfiguration so every request reaches the
origin, as suggested in review. This also removes the UseQueryString setting
from the previous commit, which is no longer needed.

- /healthz returns Cache-Control: no-store, so a health probe is never
  answered from a stored copy.
- Turn on App Service Always On, so the site is not unloaded after about
  20 minutes idle and the next request does not pay a cold start.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 90ef1a20-cd65-43f3-97cd-6fa484d8b0a4
@IEvangelist David Pine (IEvangelist) changed the title Cache Front Door redirects per query string Remove Front Door route cache, make /healthz no-store, enable Always On Oct 21, 2026
@IEvangelist

Copy link
Copy Markdown
Member Author

Thanks, Eric. Addressed in 5a5ea7e:

  • Removed route.CacheConfiguration, so every request reaches the origin. That also drops the UseQueryString setting.
  • /healthz now returns Cache-Control: no-store, and App Service Always On is enabled.

Not done here: the optional second route that caches only /_astro/*. I'll only add it if measurements justify it. Explicit Cache-Control on redirects is moot with no cache.

Still untested until it deploys: ETag/304 through Front Door, and whether redirects already cached at the edge are still served. The post-deploy checks are in the description.

A scratch App Service with the same shape (Premium v3 x2, elastic scale, minimum 2 instances, pre-warm 1, Always On off) answered its first request after about 21 hours idle in 277 ms server time, so the always-ready instances already keep the site loaded.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 90ef1a20-cd65-43f3-97cd-6fa484d8b0a4
@IEvangelist David Pine (IEvangelist) changed the title Remove Front Door route cache, make /healthz no-store, enable Always On Remove Front Door route cache and make /healthz no-store Oct 22, 2026
@IEvangelist
David Pine (IEvangelist) merged commit a62b64b into main Oct 22, 2026
10 checks passed
@IEvangelist
David Pine (IEvangelist) deleted the ievangelist-afd-use-query-string-caching branch October 22, 2026 14:55
David Pine (IEvangelist) added a commit that referenced this pull request Oct 23, 2026
#1942)

## Summary

Replaces the Server-Sent Events (SSE) live-status stream with a
WebSocket stream, because Azure Front Door (AFD) does not relay SSE.

### Problem

The first-party doc says it outright: "Front Door doesn't support
Server-Sent Events (SSE)"
(https://learn.microsoft.com/en-us/azure/frontdoor/standard-premium/websocket).
We confirmed it empirically for `GET /api/live/stream/`:

| Path | Result |
| --- | --- |
| Origin (App Service) | 200 `text/event-stream`, `event: state` at 0.6
s, `:hb` comment every 15 s, `Cache-Control: no-store`,
`X-Accel-Buffering: no` |
| Through AFD (`https://aspire.dev`) | 0 headers and 0 bytes, then 504
gateway timeout at ~220 s |
| Browser through AFD | `new EventSource('/api/live/stream/')` never
fires `open` |

The client seeded once from `GET /api/live/` and then relied only on
`EventSource`, so the live badge went stale in production.

### What changed

- Server (`src/statichost/StaticHost`)
- New `GET /api/live/ws` endpoint (`app.UseWebSockets()`,
KeepAliveInterval 30 s). It reuses the existing `LiveStatusBroadcaster`
/ Redis fan-out; only the transport changed.
- JSON frames: `{"type":"state","data":{...}}` (same data as the old
`state` event) and `{"type":"hb"}` every 15 s.
- Server closes after 80-100% of `StreamMaxLifetimeSeconds` (default 600
s, key name unchanged) with 1000, and with 1001 on shutdown. Client
disconnects and cancellation are handled.
  - Non-WebSocket requests to `/api/live/ws` get 400.
- The SSE endpoint `/api/live/stream` is removed (now 404). `/api/live`
snapshot is unchanged. Telemetry exclusion and the AppHost dashboard URL
now point at `/api/live/ws`.
- Client (`live-status.ts`)
- `EventSource` replaced by `WebSocket` (`ws:`/`wss:` from `location`,
path `/api/live/ws`, no trailing slash).
- Still seeds from `/api/live/`; exponential backoff with jitter;
visibility/online handling kept; DOM/CSS unchanged.
- Polling fallback: `/api/live/` is polled every 30 s whenever the
socket is not open (and the tab is visible), so the badge cannot go
stale if the socket is blocked. A 45 s stale-socket watchdog closes and
reconnects a socket that goes silent.
  - Vite dev proxy for `/api/live` gets `ws: true`.
- AppHost: `website.SiteConfig.IsWebSocketsEnabled = true`. It was NOT
set in the public AppHost, and WebSockets are off by default on App
Service, so this is required for the endpoint to work. Please review
this setting.
- Tests/docs: SSE tests replaced by `LiveWebSocketTests`; vitest and
Playwright specs updated; `Live/README.md` updated.

### AFD constraints considered

- Caching must be disabled on WebSocket routes or AFD drops the Upgrade
header. The AFD route has no cache config after #1937, so this is fine.
- Idle timeout is 5 min: the 15 s heartbeat (plus 30 s protocol
keep-alive) keeps it alive.
- Connections are closed after at most 2 h and may drop on maintenance:
the client reconnects with backoff and the polling fallback covers gaps.
- Capacity: 3,000 concurrent connections per AFD profile. The ~10 min
jittered server lifetime makes clients cycle.
- WAF only inspects the handshake. AFD health probes use HTTP and are
unaffected.

### Deploy note

The internal Azure DevOps `deploy` branch pulls from public `main`, so
it needs to be synced for this to ship (including the App Service
WebSockets setting).

## Third-party links and affiliations

None. The only new link is the first-party Microsoft Learn AFD WebSocket
doc.

## Validation

- `dotnet build tests\StaticHost.Tests\StaticHost.Tests.csproj` - passed
(0 errors; only the existing NU1902 MessagePack warning)
- `dotnet test tests\StaticHost.Tests\StaticHost.Tests.csproj --no-build
--filter "FullyQualifiedName!~Live.Redis"` - passed, 337/337 (includes
new WebSocket tests: initial state, updates, heartbeat, non-WS 400,
max-lifetime close, shutdown close, client close/abort)
- `pnpm exec vitest run --config vitest.config.ts
tests/unit/live-status.vitest.test.ts
tests/unit/astro-vite-config.vitest.test.ts` (in `src/frontend`) -
passed, 22/22
- Local round trip: ran StaticHost on `http://127.0.0.1:5099` against a
throwaway Redis container; a Node `ws` client received
`{"type":"state",...}` at 0.2 s and `{"type":"hb"}` at 15.2 s and 30.2
s, then a clean 1000 close; plain `GET /api/live/ws` returned 400 and
`/api/live/stream` returned 404.

### Not verified

- Through Front Door: production AFD fronts the currently deployed site,
which has no WS endpoint until this ships.
- `Live.Redis*` integration tests (need Aspire + Docker containers) were
not run.
- Playwright e2e specs were updated but not run.

### Post-deploy checklist

- [ ] App Service `webSocketsEnabled` is true after deploy
- [ ] Script opens `wss://aspire.dev/api/live/ws` and shows `state` +
`hb` messages for 60+ s, including past 220 s (and ideally past 5 min)
- [ ] Live badge updates in a browser on `https://aspire.dev` with the
network tab showing a 101 upgrade

---------

Co-authored-by: David Pine <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Copilot-Session: 90ef1a20-cd65-43f3-97cd-6fa484d8b0a4
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.

3 participants