On this page
- Status: Accepted (2026-11-23)
- Date: 2026-11-23
- Owners: Platform (edge delivery, web runtime, observability).
- Related: ADR 0016 (tenant domains), ADR 0044 (render plan and binding cache), ADR 0054 (attested RLS), ADR 0059 (dashboard scale budgets), Edge and loading performance, Tenant domains runbook.
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:
- Direct-to-France ingress on apex and tenant subdomains.
assets.msocloud.netwas Cloudflare-proxied (cf-cache-status: HIT), whereasmsocloud.netand*.msocloud.netresolved 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). - Suboptimal origin compression.
infra/traefik/msocloud-response.ymldeclaredencodings: [gzip, br]and only excludedtext/event-stream. Chrome (Accept-Encoding: zstd, br, gzip) receivedgzipinstead of Brotli (37,539 Bvs24,521 Bon/, +53% wire bloat), and already-compressedfont/woff2assets were re-compressed on every miss. - Anonymous public routes emitted two
Set-Cookieheaders.apps/web/src/proxy.tsrouted every non-static request throughNextAuth(edgeAuthConfig).auth(...), stamping__Host-authjs.csrf-tokenand__Secure-authjs.callback-urleven on anonymousGET /privacy,GET /, andGET /share/*. On/share/*, those cookies triggeredresponseSetsCookie: trueand suppressed thepublic, s-maxage=60edge cache header inapps/web/src/lib/share-edge-cache.ts. - Four-stage serial dashboard waterfall.
apps/web/src/app/(dashboard)/dashboards/[slug]/page.tsxfetched 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 eachFamilySlotuseEffectto dynamically import its widget family (preloadWidgetFamiliesexisted inwidget-family-loaders.generated.tsxbut was never called byDashboardView), and only then fire batched/api/trpcdata queries across 215 ms RTT back to France. On top of that,auth/config.tsranusersandorgMembershipssequentially,(dashboard)/layout.tsxawaitedgetLauncherTilesafter the layout query batch, anddashboards/[slug]/page.tsxran formatting, session, and tenant lookups sequentially. - No field Core Web Vitals or per-stage API timing.
/api/trpcemitted only coarseServer-Timing: total;dur=..., and browser LCP, INP, CLS, TTFB, and bfcache persistence were unmeasured in production — leaving regional migration decisions ungrounded.
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), andassets.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, keepingPOST /api/admin/org-data/uploadup 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), andfrovh.msocloud.net(host management). - IP extraction preserved. Production runs
TRUSTED_PROXY_HOPS=0;apps/web/src/server/middleware/rate-limit.ts(resolveClientIp) trustscf-connecting-iponly 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 Bgzip →24,521 Bbr, -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, andapplication/zstd. - Keep
minResponseBodyBytes: 1024. - Cloudflare
no-transforminteraction: Whileapps/web/src/server/response-cache-control.tsemitsno-transformto block Cloudflare Email Obfuscation from breaking strict CSP, Cloudflare passes origin Brotli directly tobr-capable browsers (11.5 KBon/privacy) and falls back to decompressed plain text for raregzip-only clients. Once Email Obfuscation is disabled in the Cloudflare zone dashboard,no-transformcan be evaluated for removal so Cloudflare negotiateszstd/br/gzipindependently. - 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/HEADon/mso,/privacy,/terms,/help,/help/*,/share/*,/robots.txt,/sitemap.xml,/llms.txt,/api/health,/api/ready, public static paths, platform-host/;POSTon/api/csp-report,/api/rum) with zero Auth.js session cookies, zeromsocloud_uididentity anchor, zeroADMIN_ORG_COOKIE, and no?sso=parameter skipNextAuth(edgeAuthConfig).auth(...)inapps/web/src/proxy.ts. - The bypass path still mints a per-request CSP nonce and applies strict CSP headers (
buildSecuredNextResponse), runssharePublicCacheControl(...)on/share/*(restoringpublic, s-maxage=60on unlocked anonymous share links becauseSet-Cookieis now absent), and appliespreventResponseTransformation(...). apps/web/src/app/page.tsxreadsgetRequestTenant()andcookies()in parallel and skipsauth()when no session cookie is present on a platform host.- Nonced HTML safety invariant: Because
apps/web/src/app/layout.tsxstamps a per-request<script nonce={nonce}>on HTML documents, nonced HTML responses keepCache-Control: private, no-cache, no-store, no-transformand are never givenpublic, s-maxage=...at a shared CDN (except unlocked/share/*pershare-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):
- Parallel auth session lookups (
apps/web/src/auth/config.ts). Execute theuserslookup andorgMemberships JOIN organizationsquery concurrently withPromise.all(saves 1 DB RTT per authenticated RSC page and per/api/trpccall; zero session caching). - Hoisted launcher tiles (
apps/web/src/app/(dashboard)/layout.tsx,dashboard-shell-server.tsx). RungetLauncherTiles(activeOrgId)insideorgScopedChromeReads(reusing the layout's singlewithOrgContextpooled transaction instead of firing after layout completion). - Parallel dashboard page metadata/context (
apps/web/src/app/(dashboard)/dashboards/[slug]/page.tsx). RungetActiveOrgFormatting(),getRequestSession(),getRequestTenant(),searchParams,cookies(), andreadViewState()concurrently. - 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 ofdashboards/[slug]/page.tsx(only whenswitchTo === null && autoPinBrand === null && orgId === dashboard.orgId), resolve the active tab and effective view params using the exact pure functions mirrored fromDeckViewParamsProvider,usePanelFrame, andMetricWidget, prefetch up toDASHBOARD_PREFETCH_MAX_WIDGETS = 16active-tab panel frames (explore.orgDatasetPanelFrame), org-dataset metric widgets (explore.orgDatasetQuery), and standard metric widgets (explore.query) with bounded concurrencyDASHBOARD_PREFETCH_CONCURRENCY = 6viacreateTRPCOptionsProxy, serialize withdehydrate(queryClient, { serializeData: SuperJSON.serialize }), and hydrate through<HydrationBoundary>paired withhydrate: { deserializeData: SuperJSON.deserialize }inapps/web/src/trpc/provider.tsx. Any individual widget failure is caught and ignored so the client retains normal per-widget retry handling. - 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). WirepreloadWidgetFamilies(widgetFamiliesOf(...))on active-tab mount and insideselectTabso family JS chunks download in parallel instead of staggering through individualFamilySloteffects; start above-the-fold.pub-enterand.pub-load-fadereveals atopacity: 0.55(matching.pub-rise) so Chrome paints LCP at FCP instead of waiting ~1 s foropacity: 0delays.
- Guard:
apps/web/src/__tests__/dashboard-prefetch.test.tsandpnpm 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): EmitServer-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-dependencyPerformanceObserver+pageshow.persistedcollector fromChunkReloadGuardduring browser idle time (requestIdleCallback, avoiding first-load bundle growth on/and attaching zerounloadlisteners so bfcache remains eligible).POST /api/rumenforcesreadBodyCapped(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, andyng_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–10serial 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 SECURITYpinning semantics across pooled sessions without re-architecting tenant attestation. - No
experimental.inlineCsswhile@yng/ui/styles.cssis ~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
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.netand*.msocloud.net, zeroSet-Cookieheaders 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.netstays 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/uploadto chunked multipart / direct R2 upload sowww.msocloud.netcan 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.