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
feat(telemetry): enforce meter acquisition rules and improve documentation
Victor Hugo dos Santosc8b6ca37ba1a
diff --git a/backend/.eslintrc.js b/backend/.eslintrc.jsindex f901f0df9d..ba9d6e37de 100644--- a/backend/.eslintrc.js+++ b/backend/.eslintrc.js@@ -22,6 +22,20 @@ module.exports = {},root: true,overrides: [+ {+ files: ["./src/**/*"],+ excludedFiles: ["./src/lib/telemetry/*"],+ rules: {+ "no-restricted-syntax": [+ "error",+ {+ selector: "MemberExpression[property.name='getMeter']",+ message:+ "Do not acquire an OpenTelemetry meter directly. Use highCardinalityMeter (per-actor labels) or resolveCoreMeter (observable gauges) from @app/lib/telemetry/metrics."+ }+ ]+ }+ },{files: ["./e2e-test/**/*", "./src/db/migrations/**/*"],rules: {diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex fca7f7b5a9..6f5c071900 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -401,7 +401,9 @@ OpenTelemetry metric setup lives in `src/lib/telemetry/`. Instruments are define**Meter split by cardinality:**- **`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`** — have no View and carry unbounded per-actor labels. Dropped wholesale via `OTEL_DROP_HIGH_CARDINALITY_METERS=true` in multi-tenant/cloud.+- **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.++**Never let an unbounded attribute reach the SDK's `record()`, and never acquire a meter outside `src/lib/telemetry/`.** An attributes processor (the allowlist View) bounds memory because the SDK filters attributes *before* hashing them; a `DROP` aggregation does not, because it is consulted *after*. Under cumulative temporality — which `OTEL_EXPORT_TYPE=prometheus` mandates — `TemporalMetricProcessor` retains one map entry per distinct attribute set with no cardinality cap, for the lifetime of the process. So a dropped meter that is still recorded to leaks heap, which is why `OTEL_DROP_HIGH_CARDINALITY_METERS` gates at the call site (`highCardinalityMeter` / `shouldRecordHighCardinalityMetrics` in `metrics.ts`) *and* strips attributes in the View. A `no-restricted-syntax` ESLint rule blocks `getMeter` outside `src/lib/telemetry/` so a new meter can't bypass the gate; use `highCardinalityMeter` for per-actor instruments and `resolveCoreMeter` for `InfisicalCore` observable gauges.**Rules for InfisicalCore metrics:**- **No per-tenant / per-actor identifiers** as labels — no org id, user id/email, identity id, ip, user agent, request id, or free-form values (e.g. environment slug). These scale series count with customer count, which breaks CloudWatch's 1000-datapoint-per-OTLP-request limit and drives per-GB ingestion cost. Use the **audit log table** for per-org / per-actor breakdowns.diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.tsindex a3923505ab..0f6fcdc0b7 100644--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.ts+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-queue.ts@@ -1,9 +1,8 @@-import opentelemetry from "@opentelemetry/api";-import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { getConfig } from "@app/lib/config/env";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";+import { resolveCoreMeter } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { ActorType } from "@app/services/auth/auth-type";@@ -29,7 +28,7 @@ export const pamAccountRotationQueueServiceFactory = async ({}: TPamAccountRotationQueueServiceFactoryDep) => {const appCfg = getConfig();- const meter = opentelemetry.metrics.getMeter("InfisicalCore");+ const meter = resolveCoreMeter();const pendingGauge = meter.createObservableGauge("infisical.pam_credential_rotation.pending", {description: "PAM accounts overdue for rotation (nextRotationAt <= now). Sustained growth = drain can't keep up.",unit: "{account}"diff --git a/backend/src/lib/telemetry/instrumentation.ts b/backend/src/lib/telemetry/instrumentation.tsindex 31b99e3b6b..be861a2857 100644--- a/backend/src/lib/telemetry/instrumentation.ts+++ b/backend/src/lib/telemetry/instrumentation.ts@@ -85,7 +85,17 @@ const initTelemetryInstrumentation = ({if (dropHighCardinalityMeters) {HIGH_CARDINALITY_METER_NAMES.forEach((meterName) => {- views.push({ meterName, aggregation: { type: AggregationType.DROP } });+ // The empty allowlist is load-bearing, not redundant with DROP. The SDK applies the attributes+ // processor before hashing the attribute set, but consults the aggregator after: a DROP view still+ // inserts a map entry keyed by the full attribute set, and under cumulative temporality (which the+ // Prometheus exporter mandates) that entry is retained for the lifetime of the process with no+ // cardinality cap. Collapsing every point onto the empty attribute set bounds that to one entry+ // per instrument.+ views.push({+ meterName,+ aggregation: { type: AggregationType.DROP },+ attributesProcessors: [createAllowListAttributesProcessor([])]+ });});}diff --git a/backend/src/lib/telemetry/metrics.test.ts b/backend/src/lib/telemetry/metrics.test.tsnew file mode 100644index 0000000000..cc59212907--- /dev/null+++ b/backend/src/lib/telemetry/metrics.test.ts@@ -0,0 +1,87 @@+import opentelemetry from "@opentelemetry/api";++import { highCardinalityMeter, shouldRecordHighCardinalityMetrics } from "./metrics";++const mockConfig = {+ OTEL_TELEMETRY_COLLECTION_ENABLED: true,+ OTEL_DROP_HIGH_CARDINALITY_METERS: false+};++vi.mock("@app/lib/config/env", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/lib/config/env")>()),+ getConfig: () => mockConfig+}));++// resolveMeter() memoizes per meter name, so each test uses a fresh name to observe the first resolution.+let meterNameSeq = 0;+const uniqueMeterName = () => {+ meterNameSeq += 1;+ return `TestMeter${meterNameSeq}`;+};++describe("shouldRecordHighCardinalityMetrics", () => {+ beforeEach(() => {+ mockConfig.OTEL_TELEMETRY_COLLECTION_ENABLED = true;+ mockConfig.OTEL_DROP_HIGH_CARDINALITY_METERS = false;+ });++ test("records only when telemetry is enabled and the meters are not dropped", () => {+ expect(shouldRecordHighCardinalityMetrics()).toBe(true);++ mockConfig.OTEL_DROP_HIGH_CARDINALITY_METERS = true;+ expect(shouldRecordHighCardinalityMetrics()).toBe(false);++ mockConfig.OTEL_TELEMETRY_COLLECTION_ENABLED = false;+ expect(shouldRecordHighCardinalityMetrics()).toBe(false);++ mockConfig.OTEL_DROP_HIGH_CARDINALITY_METERS = false;+ expect(shouldRecordHighCardinalityMetrics()).toBe(false);+ });+});++describe("highCardinalityMeter", () => {+ beforeEach(() => {+ mockConfig.OTEL_TELEMETRY_COLLECTION_ENABLED = true;+ mockConfig.OTEL_DROP_HIGH_CARDINALITY_METERS = false;+ vi.restoreAllMocks();+ });++ // The DROP view suppresses the aggregated value but not the attribute key, which the SDK retains for+ // the lifetime of the process under cumulative temporality. Bounding that memory requires the SDK to+ // never see the measurement at all, so assert nothing reaches it rather than that nothing is exported.+ test("does not touch the SDK at all when the meters are dropped", () => {+ mockConfig.OTEL_DROP_HIGH_CARDINALITY_METERS = true;+ const getMeter = vi.spyOn(opentelemetry.metrics, "getMeter");+ const meter = highCardinalityMeter(uniqueMeterName());++ meter.createCounter("test.counter").add(1, { "client.address": "10.0.0.1" });+ meter.createHistogram("test.histogram").record(1, { "client.address": "10.0.0.1" });++ expect(getMeter).not.toHaveBeenCalled();+ });++ test("resolves the meter and records when the meters are enabled", () => {+ const getMeter = vi.spyOn(opentelemetry.metrics, "getMeter");+ const meterName = uniqueMeterName();+ const meter = highCardinalityMeter(meterName);++ meter.createCounter("test.counter").add(1);+ meter.createHistogram("test.histogram").record(1);++ expect(getMeter).toHaveBeenCalledWith(meterName);+ });++ 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");+ const meterName = uniqueMeterName();+ const counter = highCardinalityMeter(meterName).createCounter("test.counter");++ counter.add(1);+ expect(getMeter).not.toHaveBeenCalled();++ mockConfig.OTEL_TELEMETRY_COLLECTION_ENABLED = true;+ counter.add(1);+ expect(getMeter).toHaveBeenCalledWith(meterName);+ });+});diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex 7534913e54..9e688bb65a 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -29,6 +29,8 @@ const resolveMeter = (meterName: string): Meter => {return meter;};+export const resolveCoreMeter = (): Meter => resolveMeter("InfisicalCore");+type LazyMeter = {createCounter: (name: string, options?: MetricOptions) => Counter;createHistogram: (name: string, options?: MetricOptions) => Histogram;@@ -57,10 +59,40 @@ const lazyMeter = (meterName: string): LazyMeter => ({}});+const isTelemetryEnabled = () => getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED;++export const shouldRecordHighCardinalityMetrics = () =>+ isTelemetryEnabled() && !getConfig().OTEL_DROP_HIGH_CARDINALITY_METERS;++export const highCardinalityMeter = (meterName: string): LazyMeter => {+ const meter = lazyMeter(meterName);++ return {+ createCounter: (name, options) => {+ const counter = meter.createCounter(name, options);+ return {+ add: (value: number, attributes?: Attributes) => {+ if (!shouldRecordHighCardinalityMetrics()) return;+ counter.add(value, attributes);+ }+ } as Counter;+ },+ createHistogram: (name, options) => {+ const histogram = meter.createHistogram(name, options);+ return {+ record: (value: number, attributes?: Attributes) => {+ if (!shouldRecordHighCardinalityMetrics()) return;+ histogram.record(value, attributes);+ }+ } as Histogram;+ }+ };+};+// High-cardinality, per-actor meter, kept on by default for self-hosted (where per-actor visibility is// useful and cardinality is bounded by a single org); dropped in multi-tenant/cloud via// OTEL_DROP_HIGH_CARDINALITY_METERS. The pre-existing metrics below ship with per-actor labels documented in the docs.-const infisicalMeter = lazyMeter("Infisical");+const infisicalMeter = highCardinalityMeter("Infisical");// The MeterProvider applies a strict attribute allowlist (View in// instrumentation.ts) to anything emitted here, dropping high-cardinality labels at the SDK level.@@ -107,9 +139,7 @@ export const secretReadCounter = infisicalMeter.createCounter("infisical.secret.});export const recordSecretReadMetric = (params: { environment: string; secretPath: string; name?: string }) => {- const appCfg = getConfig();-- if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {+ if (shouldRecordHighCardinalityMetrics()) {const attributes: Record<string, string> = {"infisical.environment": params.environment,"infisical.secret.path": params.secretPath,@@ -188,9 +218,7 @@ export const recordKmipOperationMetric = (params: {objectId?: string;objectName?: string;}) => {- const appCfg = getConfig();-- if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {+ if (shouldRecordHighCardinalityMetrics()) {const attributes: Record<string, string> = {"infisical.kmip.operation.type": params.operationType,"infisical.organization.id": params.orgId,@@ -230,8 +258,6 @@ export const recordKmipOperationMetric = (params: {// -- New low-cardinality instruments (InfisicalCore meter) -------------------------------------------const isTelemetryEnabled = () => getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED;-// Queue worker lifecycle metrics. Wired in queue-service.ts via worker.on('completed' | 'failed' | 'stalled').export const queueJobCounter = infisicalCoreMeter.createCounter("infisical.queue.job.count", {description: "Queue jobs processed by outcome (completed or failed)",@@ -647,7 +673,7 @@ export const recordAlertDispatchOutcomeMetric = (params: { resourceType: string;// installed the real MeterProvider, so we resolve the real meter directly here (observable gauges can't// be deferred to first use like counters/histograms — the SDK pulls them on each export).export const registerInfrastructureMetrics = (db: Knex) => {- const meter = resolveMeter("InfisicalCore");+ const meter = resolveCoreMeter();// Build info: constant-value gauge that emits 1 with build identification labels on every export.const buildInfoGauge = meter.createObservableGauge("infisical.build.info", {diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex da653b557d..756e488745 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -1,4 +1,3 @@-import opentelemetry from "@opentelemetry/api";import {Job,JobSchedulerJson,@@ -36,7 +35,8 @@ import {queueJobDurationHistogram,queueJobFailureCounter,queueJobWaitHistogram,- queueStalledCounter+ queueStalledCounter,+ resolveCoreMeter} from "@app/lib/telemetry/metrics";import { QueueWorkerProfile } from "@app/lib/types";import {@@ -676,12 +676,10 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa// push, on each scrape for Prometheus). Iterates only initialized queues in queueContainer; one// snapshot covers all ~30 named queues. Failures are swallowed because metrics must never crash the app.const QUEUE_DEPTH_STATES = ["waiting", "active", "delayed", "failed"] as const;- const queueDepthGauge = opentelemetry.metrics- .getMeter("InfisicalCore")- .createObservableGauge("infisical.queue.depth", {- description: "Number of jobs in each queue state (waiting, active, delayed, failed)",- unit: "{job}"- });+ const queueDepthGauge = resolveCoreMeter().createObservableGauge("infisical.queue.depth", {+ description: "Number of jobs in each queue state (waiting, active, delayed, failed)",+ unit: "{job}"+ });queueDepthGauge.addCallback(async (observableResult) => {if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;diff --git a/backend/src/server/plugins/api-metrics.ts b/backend/src/server/plugins/api-metrics.tsindex f4a63e1959..ebe1e2d146 100644--- a/backend/src/server/plugins/api-metrics.ts+++ b/backend/src/server/plugins/api-metrics.ts@@ -1,16 +1,16 @@import { requestContext } from "@fastify/request-context";-import opentelemetry from "@opentelemetry/api";import fp from "fastify-plugin";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";+import { highCardinalityMeter, shouldRecordHighCardinalityMetrics } from "@app/lib/telemetry/metrics";-const apiMeter = opentelemetry.metrics.getMeter("API");+const apiMeter = highCardinalityMeter("API");const latencyHistogram = apiMeter.createHistogram("API_latency", {unit: "ms"});-const infisicalMeter = opentelemetry.metrics.getMeter("Infisical");+const infisicalMeter = highCardinalityMeter("Infisical");const requestCounter = infisicalMeter.createCounter("infisical.http.server.request.count", {description: "Total number of API requests to Infisical (covers both human users and machine identities)",@@ -24,6 +24,10 @@ const requestDurationHistogram = infisicalMeter.createHistogram("infisical.http.export const apiMetrics = fp(async (fastify) => {fastify.addHook("onResponse", async (request, reply) => {+ // Checked before assembling the attribute object below: it is built per response and every label on+ // it is per-actor, so it is the largest source of the cardinality these meters would retain.+ if (!shouldRecordHighCardinalityMetrics()) return;+const { method } = request;const route = request.routeOptions.url;const { statusCode } = reply;diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.tsindex f8dd4af482..b0a585c86b 100644--- a/backend/src/server/plugins/error-handler.ts+++ b/backend/src/server/plugins/error-handler.ts@@ -1,6 +1,5 @@import { ForbiddenError, PureAbility } from "@casl/ability";import { requestContext } from "@fastify/request-context";-import opentelemetry from "@opentelemetry/api";import fastifyPlugin from "fastify-plugin";import jwt from "jsonwebtoken";import { ZodError } from "zod";@@ -25,7 +24,12 @@ import {import { classifyError } from "@app/lib/errors/classify";import { hasPostgresErrorCode, PostgresErrorCode } from "@app/lib/errors/postgres";import { RequestContextKey } from "@app/lib/request-context/request-context-keys";-import { coreHttpErrorCounter, rateLimitExceededCounter } from "@app/lib/telemetry/metrics";+import {+ coreHttpErrorCounter,+ highCardinalityMeter,+ rateLimitExceededCounter,+ shouldRecordHighCardinalityMetrics+} from "@app/lib/telemetry/metrics";enum JWTErrors {JwtExpired = "jwt expired",@@ -48,13 +52,13 @@ enum HttpStatusCodes {export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider) => {const appCfg = getConfig();- const apiMeter = opentelemetry.metrics.getMeter("API");+ const apiMeter = highCardinalityMeter("API");const errorHistogram = apiMeter.createHistogram("API_errors", {description: "API errors by type, status code, and name",unit: "1"});- const infisicalMeter = opentelemetry.metrics.getMeter("Infisical");+ const infisicalMeter = highCardinalityMeter("Infisical");const errorCounter = infisicalMeter.createCounter("infisical.http.server.error.count", {description: "Total number of API errors in Infisical (covers both human users and machine identities)",unit: "{error}"@@ -101,77 +105,80 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProviderif (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {const { method } = req;const route = req.routeOptions.url;- const errorType =- error instanceof jwt.JsonWebTokenError ? "TokenError" : error.constructor.name || "UnknownError";- errorHistogram.record(1, {- route,- method,- type: errorType,- name: error.name- });+ if (shouldRecordHighCardinalityMetrics()) {+ const errorType =+ error instanceof jwt.JsonWebTokenError ? "TokenError" : error.constructor.name || "UnknownError";- const orgId = requestContext.get(RequestContextKey.OrgId);- const orgName = requestContext.get(RequestContextKey.OrgName);- const userAuthInfo = requestContext.get(RequestContextKey.UserAuthInfo);- const identityAuthInfo = requestContext.get(RequestContextKey.IdentityAuthInfo);- const projectDetails = requestContext.get(RequestContextKey.ProjectDetails);+ errorHistogram.record(1, {+ route,+ method,+ type: errorType,+ name: error.name+ });- const attributes: Record<string, string | number> = {- "http.request.method": method,- "http.route": route ?? "",- "error.type": errorType,- "error.name": error.name- };+ const orgId = requestContext.get(RequestContextKey.OrgId);+ const orgName = requestContext.get(RequestContextKey.OrgName);+ const userAuthInfo = requestContext.get(RequestContextKey.UserAuthInfo);+ const identityAuthInfo = requestContext.get(RequestContextKey.IdentityAuthInfo);+ const projectDetails = requestContext.get(RequestContextKey.ProjectDetails);- if (orgId) {- attributes["infisical.organization.id"] = orgId;- }- if (orgName) {- attributes["infisical.organization.name"] = orgName;- }+ const attributes: Record<string, string | number> = {+ "http.request.method": method,+ "http.route": route ?? "",+ "error.type": errorType,+ "error.name": error.name+ };- if (userAuthInfo) {- if (userAuthInfo.userId) {- attributes["infisical.user.id"] = userAuthInfo.userId;+ if (orgId) {+ attributes["infisical.organization.id"] = orgId;}- if (userAuthInfo.email) {- attributes["infisical.user.email"] = userAuthInfo.email;+ if (orgName) {+ attributes["infisical.organization.name"] = orgName;}- }- if (identityAuthInfo) {- if (identityAuthInfo.identityId) {- attributes["infisical.identity.id"] = identityAuthInfo.identityId;+ if (userAuthInfo) {+ if (userAuthInfo.userId) {+ attributes["infisical.user.id"] = userAuthInfo.userId;+ }+ if (userAuthInfo.email) {+ attributes["infisical.user.email"] = userAuthInfo.email;+ }}- if (identityAuthInfo.identityName) {- attributes["infisical.identity.name"] = identityAuthInfo.identityName;- }- if (identityAuthInfo.authMethod) {- attributes["infisical.auth.method"] = identityAuthInfo.authMethod;++ if (identityAuthInfo) {+ if (identityAuthInfo.identityId) {+ attributes["infisical.identity.id"] = identityAuthInfo.identityId;+ }+ if (identityAuthInfo.identityName) {+ attributes["infisical.identity.name"] = identityAuthInfo.identityName;+ }+ if (identityAuthInfo.authMethod) {+ attributes["infisical.auth.method"] = identityAuthInfo.authMethod;+ }}- }- if (projectDetails) {- if (projectDetails.id) {- attributes["infisical.project.id"] = projectDetails.id;+ if (projectDetails) {+ if (projectDetails.id) {+ attributes["infisical.project.id"] = projectDetails.id;+ }+ if (projectDetails.name) {+ attributes["infisical.project.name"] = projectDetails.name;+ }}- if (projectDetails.name) {- attributes["infisical.project.name"] = projectDetails.name;++ const userAgent = req.headers["user-agent"];+ if (userAgent) {+ attributes["user_agent.original"] = userAgent;}- }- const userAgent = req.headers["user-agent"];- if (userAgent) {- attributes["user_agent.original"] = userAgent;- }+ if (req.realIp) {+ attributes["client.address"] = req.realIp;+ }- if (req.realIp) {- attributes["client.address"] = req.realIp;+ errorCounter.add(1, attributes);}- errorCounter.add(1, attributes);-const coreAttrs: Record<string, string | number> = {"http.request.method": method,"http.route": route ?? "unknown",diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex b05c507b44..aa43a1384f 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -1,5 +1,4 @@/* eslint-disable no-await-in-loop */-import opentelemetry from "@opentelemetry/api";import * as x509 from "@peculiar/x509";import { AxiosError } from "axios";import { Job } from "bullmq";@@ -14,6 +13,7 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-serviceimport { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";+import { highCardinalityMeter } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import { ActorType } from "@app/services/auth/auth-type";@@ -118,7 +118,7 @@ export const pkiSyncQueueFactory = ({}: TPkiSyncQueueFactoryDep) => {const appCfg = getConfig();- const integrationMeter = opentelemetry.metrics.getMeter("PkiSyncs");+ const integrationMeter = highCardinalityMeter("PkiSyncs");const syncCertificatesErrorHistogram = integrationMeter.createHistogram("pki_sync_sync_certificates_errors", {description: "PKI Sync - sync certificates errors",unit: "1"diff --git a/backend/src/services/project-env/project-env-queue.ts b/backend/src/services/project-env/project-env-queue.tsindex d72c8d0e5a..1fea421b22 100644--- a/backend/src/services/project-env/project-env-queue.ts+++ b/backend/src/services/project-env/project-env-queue.ts@@ -1,10 +1,9 @@-import opentelemetry from "@opentelemetry/api";-import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";+import { resolveCoreMeter } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { ActorType } from "@app/services/auth/auth-type";@@ -57,7 +56,7 @@ export const projectEnvQueueFactory = ({logger.warn("Project environment hard-delete cron is in development mode.");}- const meter = opentelemetry.metrics.getMeter("InfisicalCore");+ const meter = resolveCoreMeter();// Per-pod, last-tick value: only the pod that won the cron redlock updates this; other pods report 0.// Alarms must aggregate with max() across pods, else a "stuck at cap" backlog gets diluted to ~0.let lastDiscoveryCount = 0;diff --git a/backend/src/services/project/project-cleanup-queue.ts b/backend/src/services/project/project-cleanup-queue.tsindex daa53f433a..be17e63be0 100644--- a/backend/src/services/project/project-cleanup-queue.ts+++ b/backend/src/services/project/project-cleanup-queue.ts@@ -1,11 +1,10 @@-import opentelemetry from "@opentelemetry/api";-import { AccessScope } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";+import { resolveCoreMeter } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { ActorType } from "../auth/auth-type";@@ -80,7 +79,7 @@ export const projectCleanupQueueFactory = ({}// ── observability ─────────────────────────────────────────────────────────────- const meter = opentelemetry.metrics.getMeter("InfisicalCore");+ const meter = resolveCoreMeter();// Per-pod, last-tick value: only the pod that won the cron redlock updates this; other pods report 0.// Alarms must aggregate with max() across pods, else a "stuck at cap" backlog gets diluted to ~0.let lastDiscoveryCount = 0;diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.tsindex 553e2baccb..387a775522 100644--- a/backend/src/services/secret-sync/secret-sync-queue.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.ts@@ -1,4 +1,3 @@-import opentelemetry from "@opentelemetry/api";import { AxiosError, isAxiosError } from "axios";import { Job } from "bullmq";import { randomUUID } from "crypto";@@ -13,7 +12,7 @@ import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";-import { recordSecretSyncOutcomeMetric } from "@app/lib/telemetry/metrics";+import { highCardinalityMeter, recordSecretSyncOutcomeMetric } from "@app/lib/telemetry/metrics";import { triggerWorkflowIntegrationNotification } from "@app/lib/workflow-integrations/trigger-notification";import { TriggerFeature } from "@app/lib/workflow-integrations/types";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";@@ -194,7 +193,7 @@ export const secretSyncQueueFactory = ({}: TSecretSyncQueueFactoryDep) => {const appCfg = getConfig();- const integrationMeter = opentelemetry.metrics.getMeter("SecretSyncs");+ const integrationMeter = highCardinalityMeter("SecretSyncs");const syncSecretsErrorHistogram = integrationMeter.createHistogram("secret_sync_sync_secrets_errors", {description: "Secret Sync - sync secrets errors",unit: "1"diff --git a/backend/src/services/secret/secret-queue.ts b/backend/src/services/secret/secret-queue.tsindex ee189194bf..fdf6daf3e6 100644--- a/backend/src/services/secret/secret-queue.ts+++ b/backend/src/services/secret/secret-queue.ts@@ -1,5 +1,4 @@/* eslint-disable no-await-in-loop */-import opentelemetry from "@opentelemetry/api";import { AxiosError } from "axios";import { randomUUID } from "crypto";import { Knex } from "knex";@@ -25,6 +24,7 @@ import { getTimeDifferenceInSeconds, groupBy, isSamePath, unique } from "@app/liimport { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";+import { highCardinalityMeter } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";import { createManySecretsRawFnFactory, updateManySecretsRawFnFactory } from "@app/services/secret/secret-fns";@@ -198,7 +198,7 @@ export const secretQueueFactory = ({projectFolderGrantDAL,orgDAL}: TSecretQueueFactoryDep) => {- const integrationMeter = opentelemetry.metrics.getMeter("Integrations");+ const integrationMeter = highCardinalityMeter("Integrations");const errorHistogram = integrationMeter.createHistogram("integration_secret_sync_errors", {description: "Integration secret sync errors",unit: "1"diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdxindex 339400ed4a..9f60296d5f 100644--- a/docs/self-hosting/configuration/envars.mdx+++ b/docs/self-hosting/configuration/envars.mdx@@ -1103,7 +1103,7 @@ If the export type is set to `otlp`, you will have to configure a value for `OTE</ParamField><ParamField query="OTEL_DROP_HIGH_CARDINALITY_METERS" type="string" default="false" optional>- When set to `true`, the SDK discards all data points from the high-cardinality, per-actor `Infisical`, `API`, `SecretSyncs`, `PkiSyncs`, and `Integrations` meters before aggregation. The instruments still exist in code (no errors), but nothing is stored or exported. Only bounded-cardinality `InfisicalCore` metrics are emitted. Useful for large or multi-tenant deployments where per-actor label cardinality is too expensive. See [Monitoring & Telemetry](/self-hosting/guides/monitoring-telemetry#available-metrics) for details.+ When set to `true`, Infisical stops recording to the high-cardinality, per-actor `Infisical`, `API`, `SecretSyncs`, `PkiSyncs`, and `Integrations` meters. Nothing is measured, stored, exported, or held in memory for them; the instruments still exist in code, so nothing errors. Only bounded-cardinality `InfisicalCore` metrics are emitted. Recommended for large or multi-tenant deployments: while these meters are enabled and `OTEL_EXPORT_TYPE=prometheus`, memory use grows with the number of distinct label combinations recorded since startup. See [Monitoring & Telemetry](/self-hosting/guides/monitoring-telemetry#available-metrics) for details.</ParamField>## Identity Auth Methoddiff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdxindex 5cd88b7100..dc90647058 100644--- a/docs/self-hosting/guides/monitoring-telemetry.mdx+++ b/docs/self-hosting/guides/monitoring-telemetry.mdx@@ -347,7 +347,24 @@ Infisical emits metrics on two OpenTelemetry meters simultaneously. Choose whichAll 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.-To eliminate the in-memory cost of the high-cardinality meters entirely, set `OTEL_DROP_HIGH_CARDINALITY_METERS=true`. When enabled, the SDK discards all data points from the `Infisical`, `API`, `SecretSyncs`, `PkiSyncs`, and `Integrations` meters before aggregation. The instruments still exist in code (no errors), but nothing is stored or exported. Only `InfisicalCore` metrics are emitted. Defaults to `false`.+To eliminate the cost of the high-cardinality meters entirely, set `OTEL_DROP_HIGH_CARDINALITY_METERS=true`. Infisical then stops recording to the `Infisical`, `API`, `SecretSyncs`, `PkiSyncs`, and `Integrations` meters altogether, so nothing is measured, stored, exported, or held in memory for them. The instruments still exist in code, so nothing errors. Only `InfisicalCore` metrics are emitted. Defaults to `false`.++<Warning>+ **With the high-cardinality meters enabled, memory use grows with label cardinality.** Prometheus+ requires cumulative metrics, so with `OTEL_EXPORT_TYPE=prometheus` the SDK keeps one entry in memory+ for every distinct label combination it has recorded since the process started, and never releases+ them. `client.address`, `user_agent.original`, `secret.path`, and `secret.name` have no natural+ ceiling, so on a busy instance this shows up as heap that climbs with uptime and longer garbage+ collection pauses.++ This is fine for a single-organization deployment with a stable set of users, IP addresses, and+ clients: the label combinations converge and the memory does too. If you serve many organizations,+ many source IPs, or many client versions, set `OTEL_DROP_HIGH_CARDINALITY_METERS=true` and get+ per-actor detail from audit logs instead. Restarting the instance releases the memory.++ `OTEL_EXPORT_TYPE=otlp` is not affected: it exports delta metrics, so each push interval starts+ fresh and nothing accumulates across the process lifetime.+</Warning>For per-user / per-identity / per-IP / per-project breakdowns, query the audit log table. It carries `actorId`, `actorType`, `projectId`, `ip`, `userAgent` and full event detail. Metrics give you the *rate* and *latency*; audit logs give you the *who* and *where*.