Skip to content
MSO CloudDocumentation

ADR 0064 — Edge delivery, compression, and single-trip dashboard streaming

On this page

Context#

Production runs on a single high-capacity host in Gravelines, France (37.187.147.65, OVHcloud), while primary users operate from Vietnam (Ho Chi Minh City and Hanoi). Direct cross-continental network round-trips measure 210–230 ms RTT (TCP + TLS handshake alone costs ~450–650 ms before the first application byte leaves origin).

End-to-end inspection of the live production path and application runtime on 2026-11-23 isolated five concrete latency amplifiers that stack on top of geography:

  1. Direct-to-France ingress on apex and tenant subdomains. assets.msocloud.net was Cloudflare-proxied (cf-cache-status: HIT), whereas msocloud.net and *.msocloud.net resolved directly to France (proxied: false), forcing every Vietnam browser to complete TLS handshakes and packet recovery across ~215 ms RTT instead of terminating TLS at a regional Cloudflare PoP (45–90 ms RTT).
  2. Suboptimal origin compression. infra/traefik/msocloud-response.yml declared encodings: [gzip, br] and only excluded text/event-stream. Chrome (Accept-Encoding: zstd, br, gzip) received gzip instead of Brotli (37,539 B vs 24,521 B on /, +53% wire bloat), and already-compressed font/woff2 assets were re-compressed on every miss.
  3. Anonymous public routes emitted two Set-Cookie headers. apps/web/src/proxy.ts routed every non-static request through NextAuth(edgeAuthConfig).auth(...), stamping __Host-authjs.csrf-token and __Secure-authjs.callback-url even on anonymous GET /privacy, GET /, and GET /share/*. On /share/*, those cookies triggered responseSetsCookie: true and suppressed the public, s-maxage=60 edge cache header in apps/web/src/lib/share-edge-cache.ts.
  4. Four-stage serial dashboard waterfall. apps/web/src/app/(dashboard)/dashboards/[slug]/page.tsx fetched widget configuration only, sending zero widget data with HTML. After HTML arrived, the browser had to download and hydrate ~340 KB gzip JS, wait for each FamilySlot useEffect to dynamically import its widget family (preloadWidgetFamilies existed in widget-family-loaders.generated.tsx but was never called by DashboardView), and only then fire batched /api/trpc data queries across 215 ms RTT back to France. On top of that, auth/config.ts ran users and orgMemberships sequentially, (dashboard)/layout.tsx awaited getLauncherTiles after the layout query batch, and dashboards/[slug]/page.tsx ran formatting, session, and tenant lookups sequentially.
  5. No field Core Web Vitals or per-stage API timing. /api/trpc emitted only coarse Server-Timing: total;dur=..., and browser LCP, INP, CLS, TTFB, and bfcache persistence were unmeasured in production — leaving regional migration decisions ungrounded.
Cold dashboard load from Vietnam: before vs after ADR 0064Horizontal scale: 0 ms to 3,600 ms (215 ms direct VN–FR RTT; 55 ms VN–Edge RTT)0 s1.0 s2.0 s3.0 sBefore — 4 serial stages across 215 ms RTT (~2.7–3.6 s to data)1. TLS + HTML~900 ms (direct FR, gzip)2. JS + hydrate~900 ms (340 KB gz + parse)3. Chunk + tRPCFamily chunktRPC round-trip FRAfter — Edge TLS + Brotli + RSC panel prefetch + eager family preload (~1.0–1.5 s)1. Edge + RSCEdge H3 + parallel RSC2. Hydrate dataHydrationBoundary3. Preload + paintParallel family JS0 extra data RTT
Before vs after ADR 0064: server-side panel prefetching and eager family preloading remove the post-hydration cross-continental data round-trip.

Decisions#

D1 — Edge ingress policy on Cloudflare Free

Keep Cloudflare Free as the edge ingress for public and tenant traffic without breaking 2 GiB archive uploads or customer white-label CNAME chains:

  • Proxied (orange-cloud): msocloud.net (apex), *.msocloud.net (org workspace subdomains), and assets.msocloud.net (/_next/static/*, immutable CDN cache). Proxying terminates TLS/HTTP3 at regional Cloudflare PoPs (Vietnam/Singapore) and reuses persistent HTTP/2 origin connections to France.
  • DNS-only (grey-cloud): www.msocloud.net (canonical admin/upload host, keeping POST /api/admin/org-data/upload up to 2 GiB outside Cloudflare Free's 100 MB request-body cap until multipart chunked uploads or direct object-storage uploads retire that single-request stream), origin.msocloud.net (stable white-label CNAME target so customer DNS zones never trigger Cloudflare Error 1014), and frovh.msocloud.net (host management).
  • IP extraction preserved. Production runs TRUSTED_PROXY_HOPS=0; apps/web/src/server/middleware/rate-limit.ts (resolveClientIp) trusts cf-connecting-ip only when Traefik's immediate peer IP falls inside Cloudflare's published ranges (apps/web/src/server/middleware/cloudflare-ranges.ts).
  • White-label acceleration path. Customer custom domains can later onboard through Cloudflare for SaaS (100 free custom hostnames on Cloudflare Free) pointing fallback origin to origin.msocloud.net, keeping per-hostname TLS without Error 1014.

D2 — Origin compression prefers Brotli and excludes pre-compressed media

Update infra/traefik/msocloud-response.yml (and the host balancer mirror /opt/apps/balancer/dynamic/msocloud-response.yml):

  • Set encodings: [br, gzip] so modern browsers (Accept-Encoding: zstd, br, gzip) receive Brotli first (verified live on /: 37,539 B gzip → 24,521 B br, -34.7%).
  • Exclude text/event-stream (unbuffered SSE), font/woff2, font/woff, image/avif, image/webp, image/jpeg, image/png, image/gif, image/x-icon, video/mp4, video/webm, video/iso.segment, audio/mp4, application/zip, application/gzip, and application/zstd.
  • Keep minResponseBodyBytes: 1024.
  • Cloudflare no-transform interaction: While apps/web/src/server/response-cache-control.ts emits no-transform to block Cloudflare Email Obfuscation from breaking strict CSP, Cloudflare passes origin Brotli directly to br-capable browsers (11.5 KB on /privacy) and falls back to decompressed plain text for rare gzip-only clients. Once Email Obfuscation is disabled in the Cloudflare zone dashboard, no-transform can be evaluated for removal so Cloudflare negotiates zstd/br/gzip independently.
  • Guard: apps/web/src/__tests__/traefik-response-middleware.test.ts.

D3 — Cookie-free anonymous public proxy path (without caching nonced HTML)

Extract apps/web/src/lib/public-proxy-bypass.ts (canBypassAuthProxy, hasAuthSessionCookie) reusing the canonical session cookie prefixes from apps/web/src/server/pdf-forwarded-cookies.ts:

  • Strictly anonymous requests (GET/HEAD on /mso, /privacy, /terms, /help, /help/*, /share/*, /robots.txt, /sitemap.xml, /llms.txt, /api/health, /api/ready, public static paths, platform-host /; POST on /api/csp-report, /api/rum) with zero Auth.js session cookies, zero msocloud_uid identity anchor, zero ADMIN_ORG_COOKIE, and no ?sso= parameter skip NextAuth(edgeAuthConfig).auth(...) in apps/web/src/proxy.ts.
  • The bypass path still mints a per-request CSP nonce and applies strict CSP headers (buildSecuredNextResponse), runs sharePublicCacheControl(...) on /share/* (restoring public, s-maxage=60 on unlocked anonymous share links because Set-Cookie is now absent), and applies preventResponseTransformation(...).
  • apps/web/src/app/page.tsx reads getRequestTenant() and cookies() in parallel and skips auth() when no session cookie is present on a platform host.
  • Nonced HTML safety invariant: Because apps/web/src/app/layout.tsx stamps a per-request <script nonce={nonce}> on HTML documents, nonced HTML responses keep Cache-Control: private, no-cache, no-store, no-transform and are never given public, s-maxage=... at a shared CDN (except unlocked /share/* per share-public-surface.test.ts). Public marketing HTML edge caching requires moving its inline theme script to a static external script or hash-based CSP first.
  • Guard: apps/web/src/__tests__/public-proxy-bypass.test.ts.

D4 — Single-trip dashboard delivery and server query parallelization

Eliminate serial server waits and post-hydration client waterfalls without violating §72 (never process-cache sessions) or §76 (route JS bundle budgets):

  1. Parallel auth session lookups (apps/web/src/auth/config.ts). Execute the users lookup and orgMemberships JOIN organizations query concurrently with Promise.all (saves 1 DB RTT per authenticated RSC page and per /api/trpc call; zero session caching).
  2. Hoisted launcher tiles (apps/web/src/app/(dashboard)/layout.tsx, dashboard-shell-server.tsx). Run getLauncherTiles(activeOrgId) inside orgScopedChromeReads (reusing the layout's single withOrgContext pooled transaction instead of firing after layout completion).
  3. Parallel dashboard page metadata/context (apps/web/src/app/(dashboard)/dashboards/[slug]/page.tsx). Run getActiveOrgFormatting(), getRequestSession(), getRequestTenant(), searchParams, cookies(), and readViewState() concurrently.
  4. Bounded server-side active-tab widget prefetch (apps/web/src/server/dashboard-prefetch-plan.ts, apps/web/src/server/dashboard-prefetch.ts). During the RSC render of dashboards/[slug]/page.tsx (only when switchTo === null && autoPinBrand === null && orgId === dashboard.orgId), resolve the active tab and effective view params using the exact pure functions mirrored from DeckViewParamsProvider, usePanelFrame, and MetricWidget, prefetch up to DASHBOARD_PREFETCH_MAX_WIDGETS = 16 active-tab panel frames (explore.orgDatasetPanelFrame), org-dataset metric widgets (explore.orgDatasetQuery), and standard metric widgets (explore.query) with bounded concurrency DASHBOARD_PREFETCH_CONCURRENCY = 6 via createTRPCOptionsProxy, serialize with dehydrate(queryClient, { serializeData: SuperJSON.serialize }), and hydrate through <HydrationBoundary> paired with hydrate: { deserializeData: SuperJSON.deserialize } in apps/web/src/trpc/provider.tsx. Any individual widget failure is caught and ignored so the client retains normal per-widget retry handling.
  5. Eager widget family preloading and immediate hero paint (apps/web/src/app/(dashboard)/dashboards/[slug]/_components/dashboard-view.tsx, apps/web/src/components/public/public.css). Wire preloadWidgetFamilies(widgetFamiliesOf(...)) on active-tab mount and inside selectTab so family JS chunks download in parallel instead of staggering through individual FamilySlot effects; start above-the-fold .pub-enter and .pub-load-fade reveals at opacity: 0.55 (matching .pub-rise) so Chrome paints LCP at FCP instead of waiting ~1 s for opacity: 0 delays.
  • Guard: apps/web/src/__tests__/dashboard-prefetch.test.ts and pnpm run performance:budget.

D5 — Granular Server-Timing and bounded-cardinality field RUM

Instrument the live path so optimization impact and regional migration triggers are measured, not guessed:

  • API timing (apps/web/src/app/api/trpc/[trpc]/route.ts): Emit Server-Timing: auth;dur=..., rl;dur=..., exec;dur=..., total;dur=... (zero tenant identifiers or query strings).
  • Field RUM collector (apps/web/src/lib/rum-client.ts, apps/web/src/app/api/rum/route.ts, apps/web/src/server/metrics/registry.ts): Lazily load a zero-dependency PerformanceObserver + pageshow.persisted collector from ChunkReloadGuard during browser idle time (requestIdleCallback, avoiding first-load bundle growth on / and attaching zero unload listeners so bfcache remains eligible). POST /api/rum enforces readBodyCapped(req, 4096) (§138) and per-IP rate limiting (120 / 60 s), normalizes paths into 11 fixed route templates (stripping slugs and share tokens), and exports Prometheus histograms/counters: yng_web_rum_lcp_seconds, yng_web_rum_inp_seconds, yng_web_rum_cls, yng_web_rum_ttfb_seconds, and yng_web_rum_bfcache_total.
  • Guard: apps/web/src/__tests__/rum-beacon.test.ts, scripts/audit/api-body-cap.py.

D6 — Explicit boundaries (what not to build)

  • No Web-in-Singapore / DB-in-France hybrid split. Every authenticated RSC render executes multiple DB queries (m >= 4–10 serial hops including auth, RLS context, and widget reads). Separating web from Postgres across 160–185 ms FR–SG RTT turns local sub-millisecond SQL hops into 1,000–2,000 ms of cross-continental DB latency, making pages slower than direct VN → FR.
  • No Cloudflare Hyperdrive over MSOCloud's attested transactional RLS. Hyperdrive transaction pooling does not safely preserve MSOCloud's per-transaction app_set_rls_context / FORCE ROW LEVEL SECURITY pinning semantics across pooled sessions without re-architecting tenant attestation.
  • No experimental.inlineCss while @yng/ui/styles.css is ~249 KB raw. Inlining a monolithic stylesheet into every HTML document prevents browser CSS caching and inflates every uncached SSR HTML response by ~35 KB compressed.
  • No session process-caching (§72). Revocation, disabled-user checks, and identity-anchor checks remain per-request database/Redis reads.

D7 — Two-track roadmap and regional migration gate

Regional scaling law and Track A → Track B migration gateTrack A — FR Primary + Edge1. Cloudflare Free edge proxy2. Traefik Brotli + exclusions3. Zero-cookie public proxy4. RSC panel prefetch + preload5. Field RUM + Server-TimingNext levers on FR:• Multipart upload → proxy www• ECharts SVG SSR / Redis L2• Cloudflare for SaaS + R23-Condition RUM Decision GateMeasure 14 days on Prometheus:C1 · Dashboard p75 TTFB > 800 ms or interactive p75 LCP > 2.5 sC2 · Server-Timing exec p75 < 250 ms (proving RTT dominates, not SQL)C3 · Active Vietnam tenants justify co-located SG/VN primary costAll 3 true → execute Track BTrack B — Full SG / VN PrimaryMove ENTIRE state + compute:• Web + Worker + IdP (SG / VN)• Postgres primary co-located• Redis co-located (< 1 ms RTT)• Object store in region / R2Physics gain (VN users):RTT drops 215 ms → 30–50 msEvery filter click: ~60–140 msNever split Web and Postgres
Physics break-even: keeping compute and database together beats a split topology; relocate the full primary stack only when field RUM proves RTT is the dominant bottleneck.

The cross-continental break-even law is 215n > mX + δ, where n is sequential browser↔origin round-trips per interaction, m is sequential server↔DB round-trips, X is web↔DB RTT (< 1 ms when co-located vs 160–185 ms when split), and δ is replication/operational overhead. Track A minimizes n (targeting n = 1 on initial dashboard load via D4) while keeping X < 1 ms. Track B reduces the 215 ms multiplier itself to 30–50 ms by relocating compute, Postgres, Redis, and object storage together to Singapore or Vietnam once all three gate conditions hold over 14 days of yng_web_rum_* data.

Consequences#

  • Positive: Immediate 35% HTML compression reduction, edge TLS/HTTP3 termination for msocloud.net and *.msocloud.net, zero Set-Cookie headers on anonymous public routes (re-enabling /share/* 60 s edge caching), single-trip panel hydration for initial dashboard loads, and live Prometheus visibility into field CWV and per-stage tRPC timings.
  • Trade-offs: Server-side panel prefetching trades ~100–250 ms of server TTFB (bounded to 6 concurrent DB queries) to eliminate 1–2 full cross-continental browser round-trips (430–800 ms) plus post-hydration stall; www.msocloud.net stays DNS-only until chunked multipart backup upload removes the 2 GiB single-request body path.
  • Follow-up items: (1) Operator applies the Cloudflare Free dashboard checklist in Tenant domains runbook; (2) move /api/admin/org-data/upload to chunked multipart / direct R2 upload so www.msocloud.net can safely enable orange-cloud; (3) extend server prefetching to non-panel metric widgets and evaluate ECharts server-side SVG rendering + Redis L2 cache on hot compiled panel frames.