TypeScript
feat(relay): relay alerts, warnings and health dashboard via Alchemy (#22067)
Julius Marminge6327a639a6d3
diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.ymlindex c8a61602259..bf8591f81da 100644--- a/.github/workflows/deploy-relay.yml+++ b/.github/workflows/deploy-relay.yml@@ -41,6 +41,8 @@ jobs:RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }}RELAY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_TUNNEL_CLEANUP_MODE }}RELAY_LEGACY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_LEGACY_TUNNEL_CLEANUP_MODE }}+ RELAY_ALERT_NOTIFIER_ID: ${{ vars.RELAY_ALERT_NOTIFIER_ID }}+ RELAY_WARNING_NOTIFIER_ID: ${{ vars.RELAY_WARNING_NOTIFIER_ID }}CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }}CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }}APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }}diff --git a/docs/operations/relay-observability.md b/docs/operations/relay-observability.mdindex 848a676acc9..6a1d7579b45 100644--- a/docs/operations/relay-observability.md+++ b/docs/operations/relay-observability.md@@ -108,3 +108,39 @@ Questions these answer:) on trace_id| summarize runs = count(), failures = max(failures), backlog = max(backlog) by endpoint```++## Alerts++The stack provisions threshold monitors and a `t3-code-relay-health` dashboard from+[`infra/relay/src/monitoring.ts`](../../infra/relay/src/monitoring.ts) when the deployment sets+`RELAY_ALERT_NOTIFIER_ID`. Paging monitors go to that notifier and need two failing runs in a row.+Warnings go to `RELAY_WARNING_NOTIFIER_ID` when it is set and are otherwise only visible in Axiom.+Each monitor's description gives its healthy baseline.++Monitors count HTTP status codes, not span errors. A request the relay cuts off at its 9 s deadline+ends as an interrupted span without an error flag, but still answers 504. `/connect` 502s are+normal: offline hosts produce most of them, retried by their clients every few seconds.++**Links failing / tunnel recovery failing.** Open the dashboard's "Link failures by reason" table.+`provisioning: ensure-tunnel` or `configure-tunnel` with Cloudflare 429s on the "Cloudflare API calls+by status" chart is the #16810 failure: the account's Cloudflare API rate limit. Ask Cloudflare to+raise it, and check whether something is calling the API in a loop (tunnel recovery from hosts is the+largest caller). Slow Postgres instead points at the database or Hyperdrive.++**Environments unreachable.** Clients reach fewer hosts than usual. Check Cloudflare Tunnel status and+recent relay deploys before suspecting hosts: a host-side problem does not move this many+environments at once.++**Push delivery failing.** Look at the `relay.apns_deliveries.process_signed_job` or `relay.fcm.process`+error messages. An expired APNs key or FCM service account fails every job.++**Cloudflare API rate limited / near its limit.** The warning fires on sustained 429s; the page fires+when they are frequent enough to stall provisioning. Compare the call volume on the dashboard with the+account limit.++**Traffic dropped.** The Worker is down, a deploy broke it, or spans stopped reaching Axiom. Check+`https://relay.t3.codes/health` first.++**Links degraded / database slow.** Warnings for slow degradation. Link failures above 20% over six+hours have so far meant provisioning running into the 9 s deadline, with Postgres latency as the+usual cause.diff --git a/infra/relay/.env.example b/infra/relay/.env.exampleindex 3e7b6b1d109..87a9a1ca32c 100644--- a/infra/relay/.env.example+++ b/infra/relay/.env.example@@ -15,6 +15,13 @@ RELAY_TUNNEL_ZONE_NAME=tunnels.example.com# Ignored on prod.# RELAY_LEGACY_TUNNEL_GRACE_MINUTES=10+# Optional: relay monitors and health dashboard in Axiom. Set the notifier id+# that pages (incident.io in prod) to create them; unset creates neither, so+# personal stages never page anyone. Warnings go to their own notifier, or+# only show in Axiom when it is unset.+# RELAY_ALERT_NOTIFIER_ID=+# RELAY_WARNING_NOTIFIER_ID=+# Optional: Relay domain override# Set this only when the derived relay hostname should not be used.# RELAY_DOMAIN=relay.example.comdiff --git a/infra/relay/README.md b/infra/relay/README.mdindex 350140c9b10..edcd7341547 100644--- a/infra/relay/README.md+++ b/infra/relay/README.md@@ -141,6 +141,10 @@ The `production` GitHub environment must define these Actions variables:- `RELAY_API_ZONE_NAME`- `RELAY_TUNNEL_ZONE_NAME`- `RELAY_DOMAIN` if overriding the derived production relay domain+- `RELAY_ALERT_NOTIFIER_ID`, the Axiom notifier that relay alerts page. Without it the deployment+ creates no monitors or health dashboard. See+ [Relay alerts](../../docs/operations/relay-observability.md#alerts).+- `RELAY_WARNING_NOTIFIER_ID`, optional, the Axiom notifier for relay warnings- `CLERK_PUBLISHABLE_KEY`- `CLERK_JWT_AUDIENCE`- `CLERK_JWT_TEMPLATE`diff --git a/infra/relay/src/monitoring.ts b/infra/relay/src/monitoring.tsnew file mode 100644index 00000000000..154b2c15cc3--- /dev/null+++ b/infra/relay/src/monitoring.ts@@ -0,0 +1,308 @@+import * as Alchemy from "alchemy";+import * as Axiom from "alchemy/Axiom";+import * as Output from "alchemy/Output";+import * as Config from "effect/Config";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";++import { relayResourceNameForStage } from "./deploymentConfig.ts";++const RUNBOOK_URL =+ "https://github.com/pingdotgg/t3code/blob/main/docs/operations/relay-observability.md#alerts";++const LINK_ROUTE = `"/v1/client/environment-links"`;+const TUNNEL_ROUTES = `"/v1/environments/:environmentId/tunnel", "/v1/environments/:environmentId/tunnel/recovery"`;+const CLOUDFLARE_API = `['attributes.url.full'] startswith "https://api.cloudflare.com"`;+const STATUS = `toint(['attributes.http.response.status_code'])`;++// Status codes, not span errors: a request cut off by the relay deadline ends+// as an interrupted span with no error flag, but still answers 504.+// Below `minimum` requests the rate reads 0, so a quiet window cannot page.+const serverFailurePercent = (dataset: string, routes: string, minimum: number) =>+ [+ `['${dataset}']`,+ `| where kind == "server" and ['attributes.http.request.method'] == "POST" and ['attributes.http.route'] in (${routes})`,+ `| summarize total = count(), failed = countif(${STATUS} >= 500)`,+ `| project failure_pct = iff(total >= ${minimum}, 100.0 * failed / total, 0.0)`,+ ].join("\n");++type Severity = "page" | "warn";++interface RelayMonitor {+ readonly id: string;+ readonly severity: Severity;+ readonly name: string;+ /** Why it fires and the healthy baseline. The runbook link is appended. */+ readonly description: string;+ readonly query: (dataset: string) => string;+ readonly operator: "Above" | "AboveOrEqual" | "Below";+ readonly threshold: number;+ readonly rangeMinutes: number;+ readonly intervalMinutes?: number;+ readonly triggerFromNRuns?: number;+ readonly alertOnNoData?: boolean;+}++// Thresholds come from 2026-10-16..19 prod data: the worst healthy window,+// and the #16810 outage (Cloudflare API 429s stalling every provision).+// Paging monitors need two bad runs in a row; warnings catch the slow+// degradations an outage threshold has to ignore.+const relayMonitors: ReadonlyArray<RelayMonitor> = [+ {+ id: "RelayLinkFailureRateMonitor",+ severity: "page",+ name: "T3 Connect relay: links failing",+ description:+ "Share of POST /v1/client/environment-links (turning on T3 Connect) answering 5xx over 15 min. Healthy: median 11%, worst 75%. #16810: 87-96%.",+ query: (dataset) => serverFailurePercent(dataset, LINK_ROUTE, 20),+ operator: "Above",+ threshold: 80,+ rangeMinutes: 15,+ triggerFromNRuns: 2,+ },+ {+ id: "RelayTunnelFailureRateMonitor",+ severity: "page",+ name: "T3 Connect relay: tunnel recovery failing",+ description:+ "Share of host tunnel registration and recovery answering 5xx over 15 min. Hosts whose tunnel drops cannot come back. Healthy: median 4%, worst 52%. #16810: 83-94%.",+ query: (dataset) => serverFailurePercent(dataset, TUNNEL_ROUTES, 200),+ operator: "Above",+ threshold: 60,+ rangeMinutes: 15,+ triggerFromNRuns: 2,+ },+ {+ id: "RelayConnectReachabilityMonitor",+ severity: "page",+ name: "T3 Connect relay: environments unreachable",+ description:+ "Share of environments clients tried to reach that connected at least once in 30 min. Offline hosts keep this below 100%, and retry storms against them do not move it. Healthy: 65-72%.",+ query: (dataset) =>+ [+ `['${dataset}']`,+ `| where name == "relay.environment_connector.connect"`,+ `| extend environment = tostring(['attributes.custom']['relay.environment_id'])`,+ `| summarize environments = dcount(environment), connected = dcountif(environment, error != true)`,+ `| project reachable_pct = iff(environments >= 1000, 100.0 * connected / environments, 100.0)`,+ ].join("\n"),+ operator: "Below",+ threshold: 55,+ rangeMinutes: 30,+ triggerFromNRuns: 2,+ },+ {+ id: "RelayPushFailureRateMonitor",+ severity: "page",+ name: "T3 Connect relay: push delivery failing",+ description:+ "Share of APNs and FCM delivery jobs failing over 15 min, e.g. an expired APNs key or FCM credential. Healthy: APNs under 0.3%, FCM under 4%.",+ query: (dataset) =>+ [+ `['${dataset}']`,+ `| where name in ("relay.apns_deliveries.process_signed_job", "relay.fcm.process")`,+ `| summarize total = count(), failed = countif(error == true)`,+ `| project failure_pct = iff(total >= 100, 100.0 * failed / total, 0.0)`,+ ].join("\n"),+ operator: "Above",+ threshold: 10,+ rangeMinutes: 15,+ triggerFromNRuns: 2,+ },+ {+ id: "RelayCloudflareRateLimitedMonitor",+ severity: "page",+ name: "T3 Connect relay: Cloudflare API rate limited",+ description:+ "Cloudflare API 429s per 10 min from tunnel and DNS provisioning. Sustained at this level, links and recoveries stall. Peak before #16810: 1,286; during it: ~11k.",+ query: (dataset) =>+ `['${dataset}']\n| where ${CLOUDFLARE_API} and ${STATUS} == 429\n| summarize rate_limited = count()`,+ operator: "AboveOrEqual",+ threshold: 500,+ rangeMinutes: 10,+ triggerFromNRuns: 2,+ },+ {+ id: "RelayTrafficDroppedMonitor",+ severity: "page",+ name: "T3 Connect relay: traffic dropped",+ description:+ "Relay requests per 10 min collapsed: Worker down, broken deploy, or trace export stopped. Healthy minimum: ~69k.",+ query: (dataset) => `['${dataset}']\n| where kind == "server"\n| summarize requests = count()`,+ operator: "Below",+ threshold: 10_000,+ rangeMinutes: 10,+ triggerFromNRuns: 2,+ alertOnNoData: true,+ },+ {+ id: "RelayCloudflareRateLimitWarningMonitor",+ severity: "warn",+ name: "T3 Connect relay: Cloudflare API near its limit",+ description:+ "Any sustained Cloudflare API 429s. These bursts ran for days before #16810; raise the account limit or cut call volume before they grow.",+ query: (dataset) =>+ `['${dataset}']\n| where ${CLOUDFLARE_API} and ${STATUS} == 429\n| summarize rate_limited = count()`,+ operator: "AboveOrEqual",+ threshold: 20,+ rangeMinutes: 10,+ triggerFromNRuns: 2,+ },+ {+ id: "RelayLinkChronicFailureMonitor",+ severity: "warn",+ name: "T3 Connect relay: links degraded",+ description:+ "Share of links answering 5xx over 6 h, mostly 9 s deadline 504s from slow provisioning. Healthy days: 10-18%. Degraded days before #16810: 28-33%.",+ query: (dataset) => serverFailurePercent(dataset, LINK_ROUTE, 100),+ operator: "Above",+ threshold: 20,+ rangeMinutes: 360,+ intervalMinutes: 30,+ },+ {+ id: "RelayDatabaseLatencyMonitor",+ severity: "warn",+ name: "T3 Connect relay: database slow",+ description:+ "p90 Postgres query time over 15 min, in ms. Every relay request runs several queries in sequence, so this sets how close provisioning gets to the 9 s deadline. Healthy: ~200 ms.",+ query: (dataset) =>+ `['${dataset}']\n| where name == "postgres"\n| summarize p90 = percentile(duration, 90)\n| project p90_ms = p90 / 1000000`,+ operator: "Above",+ threshold: 500,+ rangeMinutes: 15,+ triggerFromNRuns: 2,+ },+];++interface QueryChart {+ readonly id: string;+ readonly name: string;+ readonly type: "TimeSeries" | "Table";+ readonly query: { readonly apl: string };+}++const timeSeries = (id: string, name: string, apl: string): QueryChart => ({+ id,+ name,+ type: "TimeSeries",+ query: { apl },+});++const relayDashboardCharts = (dataset: string): ReadonlyArray<QueryChart> => {+ const source = `['${dataset}']`;+ const linkRequests = `${source}\n| where kind == "server" and ['attributes.http.request.method'] == "POST" and ['attributes.http.route'] == ${LINK_ROUTE}`;+ const tunnelRequests = `${source}\n| where kind == "server" and ['attributes.http.request.method'] == "POST" and ['attributes.http.route'] in (${TUNNEL_ROUTES})`;+ return [+ timeSeries(+ "links",+ "Links by outcome",+ `${linkRequests}\n| summarize succeeded = countif(${STATUS} < 400), rejected = countif(${STATUS} >= 400 and ${STATUS} < 500), failed = countif(${STATUS} >= 500) by bin_auto(_time)`,+ ),+ timeSeries(+ "link-latency",+ "Link latency (ms, 9 s deadline)",+ `${linkRequests}\n| summarize p50 = percentile(duration, 50) / 1000000, p90 = percentile(duration, 90) / 1000000 by bin_auto(_time)`,+ ),+ timeSeries(+ "reachability",+ "Environments reachable per 30 min (%)",+ `${source}\n| where name == "relay.environment_connector.connect"\n| extend environment = tostring(['attributes.custom']['relay.environment_id'])\n| summarize environments = dcount(environment), connected = dcountif(environment, error != true) by bin(_time, 30m)\n| project _time, reachable_pct = 100.0 * connected / environments`,+ ),+ timeSeries(+ "tunnel",+ "Tunnel registration and recovery by outcome",+ `${tunnelRequests}\n| summarize succeeded = countif(${STATUS} < 400), rejected = countif(${STATUS} >= 400 and ${STATUS} < 500), failed = countif(${STATUS} >= 500) by bin_auto(_time)`,+ ),+ timeSeries(+ "cloudflare-api",+ "Cloudflare API calls by status",+ `${source}\n| where ${CLOUDFLARE_API}\n| summarize count() by bin_auto(_time), status = ${STATUS}`,+ ),+ timeSeries(+ "postgres",+ "Postgres query time (ms)",+ `${source}\n| where name == "postgres"\n| summarize p50 = percentile(duration, 50) / 1000000, p90 = percentile(duration, 90) / 1000000 by bin_auto(_time)`,+ ),+ timeSeries(+ "push",+ "Push delivery jobs",+ `${source}\n| where name in ("relay.apns_deliveries.process_signed_job", "relay.fcm.process")\n| summarize delivered = countif(error != true), failed = countif(error == true) by bin_auto(_time), service = iff(name == "relay.fcm.process", "fcm", "apns")`,+ ),+ timeSeries(+ "server-errors",+ "5xx by route",+ `${source}\n| where kind == "server" and ${STATUS} >= 500\n| summarize count() by bin_auto(_time), route = tostring(['attributes.http.route']), status = ${STATUS}`,+ ),+ {+ id: "link-failures",+ name: "Link failures by reason",+ type: "Table",+ query: {+ apl: `${source}\n| where name == "relay.environment_linker.link" and error == true\n| extend message = tostring(['status.message'])\n| summarize failures = count() by reason = case(message contains "failed during '", strcat("provisioning: ", extract("failed during '([^']+)'", 1, message)), message startswith "Managed tunnel limit reached", "managed tunnel limit reached", substring(message, 0, 80))\n| top 10 by failures`,+ },+ },+ ];+};++const notifierConfig = (name: string) =>+ Config.String(name).pipe(+ Config.option,+ Config.map(Option.flatMap((value) => Option.liftPredicate(value.trim(), Boolean))),+ );++/**+ * A deployment opts in by naming the notifier that pages (incident.io for+ * prod). Personal stages and forks leave it unset and get no monitors or+ * dashboard. Warnings go to their own notifier when one is set, and are only+ * visible in Axiom otherwise.+ */+export const RelayMonitoring = Effect.fn("RelayMonitoring")(function* (traces: Axiom.Dataset) {+ const { stage } = yield* Alchemy.Stack;+ const page = yield* notifierConfig("RELAY_ALERT_NOTIFIER_ID");+ if (Option.isNone(page)) return;+ const notifiers: Record<Severity, Option.Option<string>> = {+ page,+ warn: yield* notifierConfig("RELAY_WARNING_NOTIFIER_ID"),+ };++ for (const monitor of relayMonitors) {+ yield* Axiom.Monitor(monitor.id, {+ name: stage === "prod" ? monitor.name : `[${stage}] ${monitor.name}`,+ description: `${monitor.description} Runbook: ${RUNBOOK_URL}`,+ type: "Threshold",+ aplQuery: Output.map(traces.name, monitor.query),+ operator: monitor.operator,+ threshold: monitor.threshold,+ intervalMinutes: monitor.intervalMinutes ?? 5,+ rangeMinutes: monitor.rangeMinutes,+ triggerFromNRuns: monitor.triggerFromNRuns ?? 1,+ alertOnNoData: monitor.alertOnNoData ?? false,+ notifierIds: Option.toArray(notifiers[monitor.severity]),+ });+ }++ yield* Axiom.Dashboard("RelayHealthDashboard", {+ dashboard: Output.map(traces.name, (dataset) => {+ const charts = relayDashboardCharts(dataset);+ return {+ name: relayResourceNameForStage("t3-code-relay-health", stage),+ owner: "",+ description: `T3 Connect relay health. Alerts and runbook: ${RUNBOOK_URL}`,+ refreshTime: 60,+ schemaVersion: 2,+ timeWindowStart: "qr-now-24h",+ timeWindowEnd: "qr-now",+ charts: [...charts],+ // Two charts per row on Axiom's 12-column grid.+ layout: charts.map((chart, index) => ({+ i: chart.id,+ x: (index % 2) * 6,+ y: Math.floor(index / 2) * 6,+ w: 6,+ h: 6,+ })),+ };+ }),+ });+});diff --git a/infra/relay/src/observability.ts b/infra/relay/src/observability.tsindex db3eb17c418..ad43573802b 100644--- a/infra/relay/src/observability.ts+++ b/infra/relay/src/observability.ts@@ -9,6 +9,7 @@ import * as Schema from "effect/Schema";import * as Tracer from "effect/Tracer";import { relayResourceNameForStage } from "./deploymentConfig.ts";+import { RelayMonitoring } from "./monitoring.ts";const relayRecentSpansQuery = (dataset: string) =>[@@ -62,6 +63,8 @@ export const RelayObservability = Effect.gen(function* () {aplQuery: Output.map(traces.name, relayRecentSpansQuery),});+ yield* RelayMonitoring(traces);+return { traces, workerIngestToken, mobileIngestToken, clientIngestToken } as const;});