Request-metrics reader gates: four bounded surfaces
One rule governs every read on the request-metrics surface: the invariant check is the one claim that bills. A completed request writes exactly one telemetry row, keyed byrequest_id and attributed to your
tenant; the aggregate counts or excludes that row, it never invents one.
Four bounded surfaces decide which rows a given read sees and what the
aggregate does with them:
- Window chain — which time range the query scans.
- Origin-feature gate — whether the advanced-analytics block is enabled for your workspace.
- Latency exclusion — which status codes the latency percentiles drop.
- Pipeline skip-list — which request paths never meter a row at all.
1. Reader gates mapped to the four GET adapters
A dashboard reader or API consumer touches the request-metrics surface through four shipped GET adapters. Each resolves the same four gates before it returns a number; the table names the adapter, the question it answers, and the source of truth inapps/api/src/routes/stats.
The head aggregate (
GET /stats/analytics) sits behind the origin-feature gate (§3); the other three always-on widgets answer to the window chain (§2) and the skip-list (§5) but not the flag. The percentile readers that exclude 429s live on the sibling Developer API-analytics surface (GET /developers/api-analytics/overview, /endpoints, /by-key), covered in §4.
2. Window precedence chain: one worked curl per branch
Every time-bounded read resolves its window through one precedence order. TheusageQuerySchema in stats.controller.ts accepts start_date + end_date (a YYYY-MM-DD pair) or days (a trailing bound); request-logs.service.ts#buildRequestLogsFilter adds a legacy dateRange bucket string. Each branch resolves to a concrete startIso / endIso pair before the SQL or Cloud Logging filter runs.
A value that fails shape validation is dropped silently — you get the
default or a wider window, never a 400. The one exception is the explicit
start_date + end_date pair: a lone start_date or a lone end_date
is a programmer error and surfaces as a 400 with "start_date and end_date must be provided together", and a pair where start_date > end_date surfaces as a 400 with "start_date must be <= end_date". A shaped-but-calendar-invalid date (2026-02-30) also 400s rather than silently rolling over. Drift direction: drop for the trailing forms, clamp for the malformed pair.
Worked curl, one per branch
Assumehttps://api.orbit.devotel.io is your API base and $TOKEN is an API key with the analytics:read scope.
Branch 1 — explicit start_date + end_date (precedence 1, overrides days):
days=7. resolveRange returns startIso = 2026-09-01T00:00:00.000Z, endIso = 2026-09-30T23:59:59.999Z, days = 30. The days query param is ignored when the pair is present. No 400 — the pair is valid and ordered.
Branch 2 — trailing days=N (precedence 2, clamped at 365):
resolveRange anchors the window at “now” minus 14 days and returns days = 14.
days is capped at MAX_USAGE_DAYS = 365 by z.coerce.number().int().positive().max(MAX_USAGE_DAYS). The cap is a clamp, not a 400: the schema validates and coerces, so days=99999 resolves to a trailing-365-day window. A non-positive or non-integer days (days=0, days=-1, days=abc) fails the .int().positive() refinement and surfaces as a 400 Invalid query parameters.
Branch 3 — bucket preset (dateRange, request-logs only):
buildRequestLogsFilter maps "7d" → lookbackHours = 168 and scans the trailing 168 hours. An out-of-set value (dateRange=12m) fails DATE_RANGE_RE and falls through to the default LOOKBACK_HOURS window — a drop, not a 400.
Branch 4 — no input (default):
resolveRange returns the trailing DEFAULT_USAGE_DAYS = 30 days. For request-logs, no params resolves to LOOKBACK_HOURS.
3. Origin-feature gate: the advanced-analytics flag
TheGET /stats/analytics block (/, /summary, /channels, /volume, /delivery) sits behind a per-tenant feature flag, checked in a Fastify preHandler before the route handler runs:
preHandler short-circuits with a 403 and this envelope:
{ data, meta } envelope. The always-on widgets (GET /stats/summary, /stats/channel-health, /stats/usage, /stats/activity, /stats/dashboard, /stats/request-logs) are available to every reader with the analytics:read scope regardless of the flag.
Read FEATURE_DISABLED distinctly from a permission error. A 403 with error.code === "FEATURE_DISABLED" means “the advanced-analytics block is not enabled for this workspace” — it is not a scopes problem and retrying with a different token will not help. A permission error carries a different error.code (for example INSUFFICIENT_PERMISSIONS) and means the calling token lacks the analytics:read scope the whole /stats family requires. Treat the FEATURE_DISABLED 403 as “not enabled”, never as an error to retry. Drift direction: clamp. A disabled workspace gets a fixed 403, not a partial payload — the gate holds the surface closed rather than returning thin data.
4. Latency exclusion: 429s leave the percentiles
The latency percentiles a dashboard reader sees are computed by the Developer API-analytics surface (GET /developers/api-analytics/overview, /endpoints, /by-key). The head aggregate’s p50 / p95 are computed by this SQL (in api-analytics.controller.ts#fetchOverviewTotals):
api_key_id IS NOT NULL— measure genuine programmatic API-key traffic, not first-party dashboard/session polling (recorded with a NULLapi_key_id).status_code <> 429— exclude rate-limit rejections. A429is answered at the global rate-limitpreHandlerbefore the route handler runs, so itsduration_msis pure rejection overhead (a few milliseconds). Folding it in would pull the rendered p50 far below your real handler latency.
total_requests, error_count) still count every metered row — 429s included — so the error-rate and request-count cards stay honest. Only the quality metrics (latency here, and the error_rate card’s api_key_errors / api_key_count) are scoped; the volume counts stay all-traffic.
Worked example: a real 429 row and how the p50 differs
Consider a 24-hour window where a tenant made 10 genuine API-key calls, each served in ~600 ms, and hit the rate limiter 2,000 times (each rejected in ~3 ms). Theapi_request_metrics table holds 2,010 rows for that window.
One real 429 row (as it sits in public.api_request_metrics):
Without the
status_code <> 429 exclusion — the 2,000 three-millisecond 429 rows dominate the ordered set and the percentile collapses:
status_code <> 429 exclusion (the shipped behaviour) — the 2,000 rejections are dropped from the latency scope, leaving the 10 genuine rows:
total_requests card still reads 2,010; only the latency percentiles are scoped to served traffic. Drift direction: degrade. A 429 spike lowers the aggregate numerator while the latency percentile stays pinned to the served subset; the band coarsens toward served traffic, which is the intended shape, not a contradiction.
When the api-key-scoped FILTER matches zero rows — a tenant whose only API-key traffic in the window was all 429s, or no API-key traffic at all — percentile_cont returns NULL, and the response carries p50_latency_ms: null (not 0). The card renders its — unavailable placeholder, which means “nothing to measure in this scope”, not “zero latency”.
5. Pipeline skip-list: which paths never meter
The write side names its self-observation and keepalive paths on an explicit skip list rather than a blanket “everything authenticated counts” line. A row whose normalisedpath_pattern matches the skip list never enters the aggregate, so the percentiles measure genuine API traffic instead of the dashboard tab that rendered them. The constant is shouldMeterPath in apps/api/src/plugins/request-metrics.ts; the read side mirrors the same constants (API_ANALYTICS_PATH_PREFIX, DEVELOPER_USAGE_STATS_PATH, REQUEST_LOGS_READ_PATH, REALTIME_TRANSPORT_PATHS) to also exclude historical rows metered before the skip shipped.
The polled
/api/v1/stats/* widget reads (/stats/summary, /stats/dashboard, etc.) are deliberately not on the skip list: an operator opened the page, so that traffic counts as operator intent. The distinction the list draws is operator-intent, not “anything fast”.
6. Cross-route drift: reconciling rows metered before the skip shipped
The write-side skip stops new rows from enteringapi_request_metrics, but rows captured before the skip shipped still sit in the table and only age out after the window’s full span (up to 30 days). On a quiet tenant those thousands of successful sub-20 ms poll rows would otherwise dominate the dataset and collapse the rendered p50/p95 below real-traffic latency for up to a month.
The read side closes that drift with EXCLUDE_SELF_OBSERVATION, a single SQL fragment shared by every api-analytics.controller.ts aggregate. It mirrors the write-side constants so the two never drift:
api_request_metrics retains rows for up to 30 days, and the skip shipped on a known date. For any window narrower than 30 days the read-side exclusion is belt-and-braces (the write side already stopped new rows); for any window that spans the ship date the exclusion removes the pre-skip rows so the window reads correctly the moment the read-side filter deploys, rather than thinning over a few days. After 30 days from the ship date the pre-skip rows have aged out entirely and the read-side filter is pure belt-and-braces against any future write-side gap. Drift direction: drop. A skipped path contributes zero rows; the counter reads operator-intent calls only, and a pre-skip row still sitting in a longer window is excluded immediately rather than persisting.
See also
- Request-metrics pipeline — the write-side hook, Redis buffer, and read surface these gates bound.
- Request Logs model — the sibling Cloud Logging read the window chain drives.
- Stats surface map — which route family answers which question.