Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
add metrics on the stream
Thiago Araujo da Silva8cba47905c20
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex d28cc2e3b5..cc9c6d31c5 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -403,6 +403,8 @@ OpenTelemetry metric setup lives in `src/lib/telemetry/`. Instruments are define- **`InfisicalCore`** — the meter for all new metrics. A strict attribute allowlist (`INFISICAL_CORE_METER_ATTRIBUTES` in `telemetry-attributes.ts`) is applied via an SDK View, so **only bounded labels survive** — HTTP method, parameterized `http.route` template, and low-cardinality enums. This is the single choke point: any attribute passed at a call site that isn't in the allowlist is silently dropped.- **Legacy `Infisical` / `API` / `SecretSyncs` / `PkiSyncs` / `Integrations`** — carry unbounded per-actor labels (`HIGH_CARDINALITY_METER_NAMES`). Disabled wholesale via `OTEL_DROP_HIGH_CARDINALITY_METERS=true` in multi-tenant/cloud.+**Recording is fire-and-forget.** Every `.add()` / `.record()` and every `record*Metric` helper is wrapped in `safely()` in `metrics.ts`, so a broken exporter, a bad instrument name, or a config read before `initEnvConfig()` can never throw into the code being measured. A measurement is an observation of the work, never a step in it — so call sites do not need their own try/catch, and must not treat a metric as something that can fail. The swallow is silent because the logger is itself initialised from config.+**A new instrument goes on `InfisicalCore` and carries only bounded attributes.** The per-actor labels on the legacy meters are a deliberate exception, not a precedent: they are allowed only through `highCardinalityMeter`, so that `OTEL_DROP_HIGH_CARDINALITY_METERS` can switch them off. Do not put unbounded attributes on any other meter, and do not acquire a meter outside `src/lib/telemetry/` — ESLint blocks both `@opentelemetry/*` imports and `getMeter` access there, so use `highCardinalityMeter` for per-actor instruments and `resolveCoreMeter` for `InfisicalCore` observable gauges.The gate has to sit at the call site because **a `DROP` aggregation does not bound memory; only an attributes processor does.** The SDK filters attributes *before* hashing them (so the allowlist View is bounded) but consults the aggregator *after* (so a dropped data point has already been keyed by its full attribute set). Under cumulative temporality — which `OTEL_EXPORT_TYPE=prometheus` mandates — `TemporalMetricProcessor` then retains one entry per distinct attribute set, with no cardinality cap, for the lifetime of the process. A meter whose data points are dropped therefore still leaks heap if anything records to it, which is why the flag stops the recording (`shouldRecordHighCardinalityMetrics` in `metrics.ts`) *and* the View strips attributes. With the flag off — the self-hosted default — that retention is the operator's informed choice; the tradeoff is documented in the monitoring guide.@@ -438,6 +440,8 @@ Two properties make the TTL safe to rely on:- **It must stay above the retention window.** On a shard that is still being written the expiry is a second, coarser deadline racing the age trim. At 1 hour against 30 minutes the age trim always wins, and the TTL only ever fires on a shard that has gone quiet and that the cron no longer visits. Shortening it toward the retention window, or lengthening the cron's 10-minute interval past it, would start deleting shards out from under live writers.- **It reaps, it does not migrate.** An orphaned shard's buffered entries are dropped, not drained. To hand an event type off cleanly, leave it in `POSTHOG_AGGREGATED_EVENTS` for one release so the cron empties it first.+**Every bound above is silent when it bites, so all four limits are instrumented** (`recordTelemetryAggregation*Metric` in `lib/telemetry/metrics.ts`, labelled by event type only — the bucket id would multiply the series by 30). The retention trim reports how many entries it aged out, the parse step reports what it could not read back, and each drained shard reports the backlog it left behind, measured with `XLEN` after the drain trim (skipped entirely when OTel collection is off, since that round trip buys nothing else). Backlog is the leading signal: it rises before retention drops start, and a shard sitting near the `MAXLEN` cap is also shedding entries on write, which nothing can count. **Do not change one of these limits without reading those metrics first** — that is what they exist for, and the operator-facing version is in `docs/self-hosting/guides/monitoring-telemetry.mdx`.+Nothing reads the pre-stream `telemetry-event-*` keys, so a deploy that changes this layout drops whatever is still buffered. That is acceptable for product analytics, and it is the reason there is no migration path to maintain.### Database Configurationdiff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex bfaba51107..e6893151cd 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -185,6 +185,7 @@ export const mockKeyStore = (): TKeyStoreFactory => {return list.length;},streamAdd: async () => null,+ streamLength: async () => 0,streamRange: async () => [],streamTrim: async () => 0,streamCollect: async () => ({ entries: [], lastId: null })diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 82df95222c..5083270cf8 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -287,6 +287,7 @@ export type TKeyStoreFactory = {) => Promise<string | null>;streamRange: (key: string, start: string, end: string, count?: number) => Promise<[string, string[]][]>;streamTrim: (key: string, minId: string, inclusive?: boolean) => Promise<number>;+ streamLength: (key: string) => Promise<number>;streamCollect: (key: string,batchSize: number,@@ -566,6 +567,8 @@ export const keyStoreFactory = (return primaryRedis.xrange(key, start, end);};+ const streamLength = async (key: string) => primaryRedis.xlen(key);+const streamTrim = async (key: string, minId: string, inclusive = false) => {let id = minId;if (inclusive) {@@ -650,6 +653,7 @@ export const keyStoreFactory = (listRemove,listLength,streamAdd,+ streamLength,streamRange,streamTrim,streamCollectdiff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex e85d201ea9..6598c6b9dd 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -163,6 +163,7 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {return listStore[key]?.length ?? 0;},streamAdd: async () => null,+ streamLength: async () => 0,streamRange: async () => [],streamTrim: async () => 0,streamCollect: async () => ({ entries: [], lastId: null })diff --git a/backend/src/lib/telemetry/metrics.test.ts b/backend/src/lib/telemetry/metrics.test.tsindex cc59212907..4eb9694281 100644--- a/backend/src/lib/telemetry/metrics.test.ts+++ b/backend/src/lib/telemetry/metrics.test.ts@@ -71,6 +71,22 @@ describe("highCardinalityMeter", () => {expect(getMeter).toHaveBeenCalledWith(meterName);});+ // Every record helper in the module funnels through this wrapper, so a broken exporter or a bad+ // instrument name can never surface as an exception in the code being measured.+ test("does not throw into the call site when the SDK does", () => {+ const broken = () => {+ throw new Error("exporter broken");+ };+ vi.spyOn(opentelemetry.metrics, "getMeter").mockReturnValue({+ createCounter: broken,+ createHistogram: broken+ } as never);+ const meter = highCardinalityMeter(uniqueMeterName());++ expect(() => meter.createCounter("test.counter").add(1)).not.toThrow();+ expect(() => meter.createHistogram("test.histogram").record(1)).not.toThrow();+ });+test("stays a no-op while telemetry is disabled, then records once it is enabled", () => {mockConfig.OTEL_TELEMETRY_COLLECTION_ENABLED = false;const getMeter = vi.spyOn(opentelemetry.metrics, "getMeter");diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex 9e688bb65a..ab8a3dab10 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -36,6 +36,19 @@ type LazyMeter = {createHistogram: (name: string, options?: MetricOptions) => Histogram;};+// Recording is fire-and-forget: a measurement is an observation of the work, never a step in it, so+// nothing here may throw into a call site. The SDK can raise on a malformed instrument name or a+// broken exporter, and getConfig() is empty until initEnvConfig() runs, which is reachable from+// anything recording during boot. Swallowing is silent on purpose — the logger is itself initialised+// from config, so reporting the failure here risks throwing a second time from the handler.+const safely = (record: () => void) => {+ try {+ record();+ } catch {+ // metrics must never break the path they observe+ }+};+// Returns instrument wrappers whose underlying instrument is created on first use (after init), so it// binds to the real MeterProvider. Call sites keep using .add()/.record() exactly as before.const lazyMeter = (meterName: string): LazyMeter => ({@@ -43,8 +56,10 @@ const lazyMeter = (meterName: string): LazyMeter => ({let instrument: Counter | undefined;return {add: (value: number, attributes?: Attributes) => {- if (!instrument) instrument = resolveMeter(meterName).createCounter(name, options);- instrument.add(value, attributes);+ safely(() => {+ if (!instrument) instrument = resolveMeter(meterName).createCounter(name, options);+ instrument.add(value, attributes);+ });}} as Counter;},@@ -52,17 +67,22 @@ const lazyMeter = (meterName: string): LazyMeter => ({let instrument: Histogram | undefined;return {record: (value: number, attributes?: Attributes) => {- if (!instrument) instrument = resolveMeter(meterName).createHistogram(name, options);- instrument.record(value, attributes);+ safely(() => {+ if (!instrument) instrument = resolveMeter(meterName).createHistogram(name, options);+ instrument.record(value, attributes);+ });}} as Histogram;}});-const isTelemetryEnabled = () => getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED;+// Exported so a call site can skip work it would only do to produce a measurement (an extra query,+// a serialization, a size computation). Recording is already gated internally, so this is never+// needed to make a record*Metric call safe.+export const isTelemetryEnabled = () => Boolean(getConfig()?.OTEL_TELEMETRY_COLLECTION_ENABLED);export const shouldRecordHighCardinalityMetrics = () =>- isTelemetryEnabled() && !getConfig().OTEL_DROP_HIGH_CARDINALITY_METERS;+ isTelemetryEnabled() && !getConfig()?.OTEL_DROP_HIGH_CARDINALITY_METERS;export const highCardinalityMeter = (meterName: string): LazyMeter => {const meter = lazyMeter(meterName);@@ -668,6 +688,64 @@ export const recordAlertDispatchOutcomeMetric = (params: { resourceType: string;});};+export enum TelemetryAggregationDropReason {+ Retention = "retention",+ Unparseable = "unparseable"+}++export const telemetryAggregationPublishedCounter = infisicalCoreMeter.createCounter(+ "infisical.telemetry_aggregation.published.count",+ {+ description: "Buffered telemetry events drained from Redis and published to PostHog, by event type.",+ unit: "{event}"+ }+);++export const telemetryAggregationDroppedCounter = infisicalCoreMeter.createCounter(+ "infisical.telemetry_aggregation.dropped.count",+ {+ description:+ "Buffered telemetry events dropped before reaching PostHog, by event type and reason. Occasional retention drops are tolerable; a sustained rate means the drain is not keeping up and the limits need tweaking.",+ unit: "{event}"+ }+);++export const telemetryAggregationBacklogHistogram = infisicalCoreMeter.createHistogram(+ "infisical.telemetry_aggregation.shard.backlog",+ {+ description:+ "Entries left in a shard after its drain, by event type. Zero on a healthy run: a backlog that persists across runs is what precedes retention drops and, near the 100k MAXLEN, silent write-path eviction.",+ unit: "{entry}"+ }+);++export const recordTelemetryAggregationPublishedMetric = (params: { eventType: string; count: number }) =>+ safely(() => {+ if (!isTelemetryEnabled() || params.count === 0) return;+ telemetryAggregationPublishedCounter.add(params.count, { "telemetry_aggregation.event_type": params.eventType });+ });++export const recordTelemetryAggregationDroppedMetric = (params: {+ eventType: string;+ reason: TelemetryAggregationDropReason;+ count: number;+}) =>+ safely(() => {+ if (!isTelemetryEnabled() || params.count === 0) return;+ telemetryAggregationDroppedCounter.add(params.count, {+ "telemetry_aggregation.event_type": params.eventType,+ "telemetry_aggregation.drop_reason": params.reason+ });+ });++export const recordTelemetryAggregationBacklogMetric = (params: { eventType: string; backlog: number }) =>+ safely(() => {+ if (!isTelemetryEnabled()) return;+ telemetryAggregationBacklogHistogram.record(params.backlog, {+ "telemetry_aggregation.event_type": params.eventType+ });+ });+// -- Boot-time observable gauges (InfisicalCore meter) ----------------------------------------------// Registered once at boot from main.ts with the primary Knex instance. Runs AFTER setupTelemetry() has// installed the real MeterProvider, so we resolve the real meter directly here (observable gauges can'tdiff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.tsindex 806276dd71..6ecf8ed7e8 100644--- a/backend/src/lib/telemetry/telemetry-attributes.ts+++ b/backend/src/lib/telemetry/telemetry-attributes.ts@@ -19,6 +19,8 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = ["audit_log.actor_type","audit_log.backend","audit_log.drop_reason",+ "telemetry_aggregation.event_type",+ "telemetry_aggregation.drop_reason","audit_log_stream.provider","audit_log_stream.id","scim.operation",diff --git a/backend/src/services/telemetry/telemetry-service.test.ts b/backend/src/services/telemetry/telemetry-service.test.tsindex 6d73372279..5d5d7f23ef 100644--- a/backend/src/services/telemetry/telemetry-service.test.ts+++ b/backend/src/services/telemetry/telemetry-service.test.ts@@ -17,8 +17,10 @@ vi.mock("@app/lib/config/env", async (importOriginal) => ({getConfig: () => mockConfig}));+const loggerMock = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }));+vi.mock("@app/lib/logger", () => ({- logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }+ logger: loggerMock}));vi.mock("@fastify/request-context", () => ({@@ -37,6 +39,20 @@ vi.mock("posthog-node", () => ({PostHog: vi.fn(() => postHogClient)}));+// The drain's health signals: what it published, what it lost, and what it left behind. Spied here+// because a limit (MAXLEN, collect ceiling, retention window) can only be tuned against them.+const metrics = vi.hoisted(() => ({+ recordTelemetryAggregationPublishedMetric: vi.fn(),+ recordTelemetryAggregationDroppedMetric: vi.fn(),+ recordTelemetryAggregationBacklogMetric: vi.fn(),+ isTelemetryEnabled: vi.fn(() => true)+}));++vi.mock("@app/lib/telemetry/metrics", () => ({+ ...metrics,+ TelemetryAggregationDropReason: { Retention: "retention", Unparseable: "unparseable" }+}));+// eslint-disable-next-line import/firstimport { POSTHOG_AGGREGATED_EVENTS, telemetryServiceFactory } from "./telemetry-service";@@ -83,7 +99,8 @@ const createHarness = () => {streamCollect: vi.fn<(key: string) => Promise<{ entries: [string, string[]][]; lastId: string | null }>>(async () => ({ entries: [], lastId: null })),- streamTrim: vi.fn<(key: string, minId: string, inclusive?: boolean) => Promise<number>>(async () => 0)+ streamTrim: vi.fn<(key: string, minId: string, inclusive?: boolean) => Promise<number>>(async () => 0),+ streamLength: vi.fn<(key: string) => Promise<number>>(async () => 0)};const telemetryService = telemetryServiceFactory({@@ -99,6 +116,7 @@ const createHarness = () => {describe("telemetry aggregated event storage", () => {beforeEach(() => {vi.clearAllMocks();+ metrics.isTelemetryEnabled.mockReturnValue(true);});test("appends an aggregated event to its shard stream instead of a per-event key", async () => {@@ -378,6 +396,109 @@ describe("telemetry aggregated event storage", () => {await telemetryService.processAggregatedEvents();+ expect(postHogClient.capture).toHaveBeenCalledTimes(1);+ expect(drainTrims(keyStore)).toEqual([[streamKey, "3-0", true]]);+ });+ test("counts what the retention trim aged out as a drop, and warns once per event type", async () => {+ const { keyStore, telemetryService } = createHarness();+ const bucketId = telemetryService.getBucketForDistinctId("user-1");+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;++ keyStore.streamTrim.mockImplementation(async (key, _minId, inclusive) =>+ key === streamKey && inclusive === undefined ? 4 : 0+ );++ await telemetryService.processAggregatedEvents();++ expect(metrics.recordTelemetryAggregationDroppedMetric).toHaveBeenCalledWith({+ eventType: PostHogEventTypes.SecretPulled,+ reason: "retention",+ count: 4+ });+ expect(loggerMock.warn).toHaveBeenCalledTimes(1);+ });++ test("counts an entry it cannot parse as a drop rather than losing it silently", async () => {+ const { keyStore, telemetryService } = createHarness();+ const bucketId = telemetryService.getBucketForDistinctId("user-1");+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;++ keyStore.streamCollect.mockImplementation(async (key) => {+ if (key !== streamKey) return { entries: [], lastId: null };+ const { entries } = collectResult([pulledEvent()], "5-0");+ return { entries: [...entries, ["5-0", ["data", "{not json"]] as [string, string[]]], lastId: "5-0" };+ });++ await telemetryService.processAggregatedEvents();++ expect(metrics.recordTelemetryAggregationDroppedMetric).toHaveBeenCalledWith({+ eventType: PostHogEventTypes.SecretPulled,+ reason: "unparseable",+ count: 1+ });+ expect(metrics.recordTelemetryAggregationPublishedMetric).toHaveBeenCalledWith({+ eventType: PostHogEventTypes.SecretPulled,+ count: 1+ });+ });++ test("reports the shard backlog the run left behind, measured after the drain trim", async () => {+ const { keyStore, telemetryService } = createHarness();+ const bucketId = telemetryService.getBucketForDistinctId("user-1");+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;+ const trimmedBeforeLength: boolean[] = [];++ keyStore.streamCollect.mockImplementation(async (key) =>+ key === streamKey ? collectResult([pulledEvent()], "3-0") : { entries: [], lastId: null }+ );+ keyStore.streamLength.mockImplementation(async (key) => {+ trimmedBeforeLength.push(drainTrims(keyStore).some(([trimmedKey]) => trimmedKey === key));+ return 12;+ });++ await telemetryService.processAggregatedEvents();++ // Only the drained shard is measured; an empty shard reports zero without spending a round trip.+ expect(keyStore.streamLength).toHaveBeenCalledTimes(1);+ expect(trimmedBeforeLength).toEqual([true]);+ expect(metrics.recordTelemetryAggregationBacklogMetric).toHaveBeenCalledWith({+ eventType: PostHogEventTypes.SecretPulled,+ backlog: 12+ });+ expect(metrics.recordTelemetryAggregationBacklogMetric).toHaveBeenCalledWith({+ eventType: PostHogEventTypes.SecretPulled,+ backlog: 0+ });+ });++ test("skips the backlog round trip when nothing will export it", async () => {+ const { keyStore, telemetryService } = createHarness();+ const bucketId = telemetryService.getBucketForDistinctId("user-1");+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;++ metrics.isTelemetryEnabled.mockReturnValue(false);+ keyStore.streamCollect.mockImplementation(async (key) =>+ key === streamKey ? collectResult([pulledEvent()], "3-0") : { entries: [], lastId: null }+ );++ await telemetryService.processAggregatedEvents();++ expect(keyStore.streamLength).not.toHaveBeenCalled();+ expect(drainTrims(keyStore)).toEqual([[streamKey, "3-0", true]]);+ });++ test("publishes the batch even when the backlog measurement fails", async () => {+ const { keyStore, telemetryService } = createHarness();+ const bucketId = telemetryService.getBucketForDistinctId("user-1");+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;++ keyStore.streamCollect.mockImplementation(async (key) =>+ key === streamKey ? collectResult([pulledEvent()], "3-0") : { entries: [], lastId: null }+ );+ keyStore.streamLength.mockRejectedValue(new Error("redis hiccup"));++ await telemetryService.processAggregatedEvents();+expect(postHogClient.capture).toHaveBeenCalledTimes(1);expect(drainTrims(keyStore)).toEqual([[streamKey, "3-0", true]]);});diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.tsindex 6805dfcf76..8600fbdecb 100644--- a/backend/src/services/telemetry/telemetry-service.ts+++ b/backend/src/services/telemetry/telemetry-service.ts@@ -13,6 +13,13 @@ import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";+import {+ isTelemetryEnabled as isOtelMetricsEnabled,+ recordTelemetryAggregationBacklogMetric,+ recordTelemetryAggregationDroppedMetric,+ recordTelemetryAggregationPublishedMetric,+ TelemetryAggregationDropReason+} from "@app/lib/telemetry/metrics";import { ActorType } from "@app/services/auth/auth-type";import { TOrgDALFactory } from "@app/services/org/org-dal";import { getServerCfg } from "@app/services/super-admin/super-admin-service";@@ -69,7 +76,7 @@ export type TTelemetryServiceFactory = ReturnType<typeof telemetryServiceFactoryexport type TTelemetryServiceFactoryDep = {keyStore: Pick<TKeyStoreFactory,- "incrementBy" | "setItemWithExpiryNX" | "setExpiry" | "streamAdd" | "streamCollect" | "streamTrim"+ "incrementBy" | "setItemWithExpiryNX" | "setExpiry" | "streamAdd" | "streamCollect" | "streamTrim" | "streamLength">;licenseService: Pick<TLicenseServiceFactory, "getInstanceType" | "getPlan">;orgDAL: Pick<TOrgDALFactory, "findOrgById">;@@ -577,15 +584,35 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme);}+ const events = parseEventPayloads(entries, `event=${eventType} bucket=${bucketId}`);++ recordTelemetryAggregationDroppedMetric({+ eventType,+ reason: TelemetryAggregationDropReason.Unparseable,+ count: entries.length - events.length+ });+return {- events: parseEventPayloads(entries, `event=${eventType} bucket=${bucketId}`),+ events,collected: entries.length,lastId};};+ const recordShardBacklog = async (streamKey: string, eventType: string, bucketId: string) => {+ // The XLEN is bought solely for this metric, so it is not worth a round trip per drained shard+ // on the instances (the default) that export nothing.+ if (!isOtelMetricsEnabled()) return;++ try {+ recordTelemetryAggregationBacklogMetric({ eventType, backlog: await keyStore.streamLength(streamKey) });+ } catch (error) {+ logger.error(error, `Failed to measure backlog on bucket ${bucketId} for ${eventType}`);+ }+ };+const processBucketEvents = async (eventType: string, bucketId: string, orgsIdentifyAttempted: Set<string>) => {- if (!postHog) return 0;+ if (!postHog) return { published: 0, expired: 0 };const streamKey = KeyStorePrefixes.TelemetryAggregatedEventStream(eventType, bucketId);@@ -595,8 +622,14 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmelogger.error(error, `Failed to refresh key expiry on bucket ${bucketId} for ${eventType}`);}+ let expired = 0;try {- await keyStore.streamTrim(streamKey, `${Date.now() - TELEMETRY_EVENT_STREAM_RETENTION_MS}-0`);+ expired = await keyStore.streamTrim(streamKey, `${Date.now() - TELEMETRY_EVENT_STREAM_RETENTION_MS}-0`);+ recordTelemetryAggregationDroppedMetric({+ eventType,+ reason: TelemetryAggregationDropReason.Retention,+ count: expired+ });} catch (error) {logger.error(error, `Failed to apply retention trim to bucket ${bucketId} for ${eventType}`);}@@ -604,7 +637,10 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmetry {const { events, collected, lastId } = await collectShardEvents(streamKey, eventType, bucketId);- if (collected === 0 || !lastId) return 0;+ if (collected === 0 || !lastId) {+ recordTelemetryAggregationBacklogMetric({ eventType, backlog: 0 });+ return { published: 0, expired };+ }await publishAggregatedEvents(eventType, events, orgsIdentifyAttempted);@@ -612,11 +648,14 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmeawait keyStore.streamTrim(streamKey, lastId, true);+ recordTelemetryAggregationPublishedMetric({ eventType, count: events.length });+ await recordShardBacklog(streamKey, eventType, bucketId);+logger.info(`Processed ${events.length} events from bucket ${bucketId} for ${eventType}`);- return events.length;+ return { published: events.length, expired };} catch (error) {logger.error(error, `Failed to process bucket ${bucketId} for ${eventType}`);- return 0;+ return { published: 0, expired };}};@@ -629,6 +668,7 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmefor (const eventType of POSTHOG_AGGREGATED_EVENTS) {let totalProcessed = 0;+ let totalExpired = 0;logger.info(`Starting bucket processing for ${eventType}`);for (let i = 0; i < TELEMETRY_BUCKET_NAMES.length; i += BUCKET_CONCURRENCY) {@@ -637,10 +677,19 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmeconst results = await Promise.all(batch.map((bucketId) => processBucketEvents(eventType, bucketId, orgsIdentifyAttempted)));- totalProcessed += results.reduce((sum, n) => sum + n, 0);+ totalProcessed += results.reduce((sum, result) => sum + result.published, 0);+ totalExpired += results.reduce((sum, result) => sum + result.expired, 0);}logger.info(`Completed processing ${totalProcessed} total events for ${eventType}`);++ if (totalExpired > 0) {+ logger.warn(+ `Telemetry aggregation dropped ${totalExpired} events for ${eventType} that aged past the ${+ TELEMETRY_EVENT_STREAM_RETENTION_MS / 60_000+ }-minute retention window before they could be published`+ );+ }}};diff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdxindex 711b023d4d..798b24e732 100644--- a/docs/self-hosting/guides/monitoring-telemetry.mdx+++ b/docs/self-hosting/guides/monitoring-telemetry.mdx@@ -343,7 +343,7 @@ Replace `otel-collector:8889` with the actual hostname and port where your OpenTInfisical emits metrics on two OpenTelemetry meters simultaneously. Choose which to scrape based on your deployment scale.- **High-cardinality, per-actor meters:** the `Infisical` and `API` meters' original metrics (`infisical.http.server.request.*`, `infisical.http.server.error.count`, `infisical.secret.read.count`, `infisical.auth.attempt.count`, `infisical.kmip.operation.count`) include per-actor labels such as `user.email`, `identity.name`, `client.address`, `user_agent.original`, `organization.name`, `project.name`, `secret.path`, and `secret.name`. The `SecretSyncs`, `PkiSyncs`, and `Integrations` meters likewise carry unbounded labels such as `syncId`. Useful for self-hosted deployments where you want per-user visibility directly in Grafana. May become expensive at large scale (many users, identities, or IPs) due to label cardinality.-- **`InfisicalCore` meter (bounded-cardinality):** all newer metrics (queue, audit log, alert dispatch, permission cache, secret cache, rate limit, build info, `infisical.core.http.error.count`, authentication latency, token renewal, SSO config changes, SCIM provisioning, and database connection pool) use **only bounded enums and static route templates** as labels (e.g. HTTP method, parameterized `http.route`, error type, outcome). A strict allowlist drops every other attribute at the SDK level, so **no tenant or actor identifiers are emitted**; no organization ID, project IDs, names, emails, IPs, or user agents. This keeps the series count independent of how many organizations, users, or identities you have. Per-org and per-actor detail is available in audit logs instead.+- **`InfisicalCore` meter (bounded-cardinality):** all newer metrics (queue, audit log, product analytics aggregation, alert dispatch, permission cache, secret cache, rate limit, build info, `infisical.core.http.error.count`, authentication latency, token renewal, SSO config changes, SCIM provisioning, and database connection pool) use **only bounded enums and static route templates** as labels (e.g. HTTP method, parameterized `http.route`, error type, outcome). A strict allowlist drops every other attribute at the SDK level, so **no tenant or actor identifiers are emitted**; no organization ID, project IDs, names, emails, IPs, or user agents. This keeps the series count independent of how many organizations, users, or identities you have. Per-org and per-actor detail is available in audit logs instead.All meters emit at the same time. If you are a self-hosted instance and find the per-actor labels useful, keep using the high-cardinality metrics. For larger or multi-tenant deployments, scrape only the `InfisicalCore` metrics to keep cardinality under control.@@ -873,6 +873,54 @@ Per-provider observability for the audit-log stream feature (Datadog, Splunk, Cu</Accordion></AccordionGroup>+### Product Analytics Aggregation Metrics (InfisicalCore)++High-volume product analytics events (secret pulls, machine identity logins, certificate issuance, and similar) are buffered in Redis and rolled up by a cron every 10 minutes instead of being sent one by one. The buffer is deliberately bounded, so events that the roll-up does not reach in time are discarded. These metrics tell you whether that is happening. They are only emitted when product analytics is enabled (`TELEMETRY_ENABLED`), since the roll-up does not run otherwise.++<AccordionGroup>+ <Accordion title="Aggregation Published">+ **Metric Name**: `infisical.telemetry_aggregation.published.count`++ **Type**: Counter++ **Unit**: `{event}`++ **Description**: Buffered events drained from Redis and sent upstream. Use it as the denominator for the drop rate below.++ **Attributes**:+ - `telemetry_aggregation.event_type` (string): the buffered event, e.g. `secrets pulled`+ </Accordion>++ <Accordion title="Aggregation Dropped">+ **Metric Name**: `infisical.telemetry_aggregation.dropped.count`++ **Type**: Counter++ **Unit**: `{event}`++ **Description**: Buffered events discarded before they were sent. `retention` means the event aged past the 30-minute buffer window while the roll-up was behind; `unparseable` means its payload could not be read back and points at a bug rather than at capacity.++ **Attributes**:+ - `telemetry_aggregation.event_type` (string)+ - `telemetry_aggregation.drop_reason` (string): `retention` or `unparseable`+ </Accordion>++ <Accordion title="Aggregation Shard Backlog">+ **Metric Name**: `infisical.telemetry_aggregation.shard.backlog`++ **Type**: Histogram++ **Unit**: `{entry}`++ **Description**: Entries left in a buffer shard after the roll-up finished with it. Zero on a healthy run.++ **Attributes**:+ - `telemetry_aggregation.event_type` (string)+ </Accordion>+</AccordionGroup>++**What to alarm on**: a sustained `retention` drop rate, and any `unparseable` drop at all. Losing a few analytics events occasionally costs nothing, but a rate that does not return to zero means the roll-up is permanently behind the write rate. The backlog histogram is the early warning: it rises before drops start, and a shard sitting near 100,000 entries is also shedding the oldest events on write, invisibly to the drop counter.+### Alert Dispatch Metrics (InfisicalCore)Every "notify me when X happens" alert (credential expiry and anything else built on the alert module) is delivered by a dispatch job. This metric records how each job ended, so you can tell a dropped notification apart from a job that had nothing to send.