:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): emit per-team ingested counters into posthog metrics (#72976)
Daniel Visca71421234aee8
diff --git a/nodejs/src/ingestion/pipelines/metrics/ingestion-otel-metrics.test.ts b/nodejs/src/ingestion/pipelines/metrics/ingestion-otel-metrics.test.tsnew file mode 100644index 000000000000..23a225a43c65--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/ingestion-otel-metrics.test.ts@@ -0,0 +1,83 @@+import { metrics as metricsApi } from '@opentelemetry/api'+import {+ type DataPoint,+ InMemoryMetricExporter,+ MeterProvider,+ PeriodicExportingMetricReader,+} from '@opentelemetry/sdk-metrics'++import { recordMetricsIngested, resetMetricsIngestionInstrumentsForTests } from './ingestion-otel-metrics'++describe('ingestion-otel-metrics', () => {+ let exporter: InMemoryMetricExporter+ let provider: MeterProvider+ let reader: PeriodicExportingMetricReader++ beforeEach(() => {+ // Simulate the real startup-order hazard: a record call may run before a+ // provider exists (bound to the noop meter), with the provider registered+ // afterwards. Lazily acquired instruments must still deliver data recorded+ // after registration.+ resetMetricsIngestionInstrumentsForTests()+ recordMetricsIngested(1, 1, 1)++ exporter = new InMemoryMetricExporter(0)+ reader = new PeriodicExportingMetricReader({ exporter, exportIntervalMillis: 60_000 })+ provider = new MeterProvider({ readers: [reader] })+ metricsApi.setGlobalMeterProvider(provider)+ resetMetricsIngestionInstrumentsForTests()+ })++ afterEach(async () => {+ await provider.shutdown()+ metricsApi.disable()+ })++ const dataPointsFor = <T>(name: string): readonly DataPoint<T>[] =>+ exporter+ .getMetrics()+ .flatMap((rm) => rm.scopeMetrics)+ .flatMap((sm) => sm.metrics)+ .filter((m) => m.descriptor.name === name)+ .flatMap((m) => m.dataPoints as unknown as readonly DataPoint<T>[])++ it.each([+ ['bytes', 'metrics_ingestion_bytes_ingested_total', 2048],+ ['records', 'metrics_ingestion_records_ingested_total', 10],+ ] as const)('emits per-team ingested %s', async (_name, metricName, value) => {+ recordMetricsIngested(42, 2048, 10)++ await reader.forceFlush()++ const points = dataPointsFor<number>(metricName)+ expect(points).toHaveLength(1)+ expect(points[0].attributes).toEqual({ team_id: '42' })+ expect(points[0].value).toEqual(value)+ })++ it('skips zero and negative amounts so no empty per-team series are created', async () => {+ recordMetricsIngested(42, 0, 0)+ recordMetricsIngested(43, -1, 0)++ await reader.forceFlush()++ const names = ['metrics_ingestion_bytes_ingested_total', 'metrics_ingestion_records_ingested_total']+ expect(names.map((name) => dataPointsFor(name).length)).toEqual([0, 0])+ })++ it('swallows a throwing OTel SDK so the consumer background task is never rejected', () => {+ const throwing = () => {+ throw new Error('otel exploded')+ }+ metricsApi.disable() // the API ignores a second setGlobalMeterProvider without this+ metricsApi.setGlobalMeterProvider({+ getMeter: () =>+ ({+ createCounter: () => ({ add: throwing }),+ }) as any,+ } as any)+ resetMetricsIngestionInstrumentsForTests()++ expect(() => recordMetricsIngested(42, 1, 1)).not.toThrow()+ })+})diff --git a/nodejs/src/ingestion/pipelines/metrics/ingestion-otel-metrics.ts b/nodejs/src/ingestion/pipelines/metrics/ingestion-otel-metrics.tsnew file mode 100644index 000000000000..9decef31891b--- /dev/null+++ b/nodejs/src/ingestion/pipelines/metrics/ingestion-otel-metrics.ts@@ -0,0 +1,63 @@+import { Attributes, Counter, metrics as metricsApi } from '@opentelemetry/api'++import { createCounterWithExemplars, swallowing } from '~/common/metrics/instruments'++/**+ * OTLP-pushed per-team ingestion counters, landing in the PostHog metrics product+ * through the exporter installed by initMetrics (common/metrics/otel-metrics.ts).+ * They answer "which teams are actually ingesting metrics" — a signal neither the+ * aggregate prom counters (no team label) nor the app_metrics2 usage rows (billing+ * store, not queryable as a metric) provide.+ *+ * Names mirror the app_metrics2 usage rows (records_ingested/bytes_ingested)+ * rather than the prom *_allowed_total counters, which already reach the metrics+ * product team-less via the scrape bridge — reusing those names would mix two+ * label schemas. The boundary here is stricter than the usage rows: recorded only+ * after a message is successfully produced to the ClickHouse-bound topic, so+ * DLQ'd messages never count as ingested.+ *+ * Instruments are acquired lazily on first record: the OTel metrics API has no proxy+ * provider, so instruments created at module load (before initMetrics runs) would be+ * bound to the noop meter forever.+ */++interface MetricsIngestionInstruments {+ bytesIngested: Counter+ recordsIngested: Counter+}++let instruments: MetricsIngestionInstruments | null = null++function getInstruments(): MetricsIngestionInstruments {+ if (instruments === null) {+ const meter = metricsApi.getMeter('metrics-ingestion')+ instruments = {+ bytesIngested: createCounterWithExemplars(meter, 'metrics_ingestion_bytes_ingested_total', {+ description: 'Total uncompressed metric bytes successfully produced for storage, by team',+ unit: 'By',+ }),+ recordsIngested: createCounterWithExemplars(meter, 'metrics_ingestion_records_ingested_total', {+ description: 'Total metric records successfully produced for storage, by team',+ }),+ }+ }+ return instruments+}++function addPositive(counter: Counter, value: number, attributes?: Attributes): void {+ if (value > 0) {+ counter.add(value, attributes)+ }+}++export const recordMetricsIngested = swallowing((teamId: number, bytes: number, records: number): void => {+ const { bytesIngested, recordsIngested } = getInstruments()+ const attributes = { team_id: teamId.toString() }+ addPositive(bytesIngested, bytes, attributes)+ addPositive(recordsIngested, records, attributes)+})++/** Test seam: forget cached instruments so a test-installed provider is picked up. */+export function resetMetricsIngestionInstrumentsForTests(): void {+ instruments = null+}diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.tsindex ad263011bc8f..da4978a13860 100644--- a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts@@ -14,6 +14,7 @@ import { TeamManager } from '~/common/utils/team-manager'import { HealthCheckResult, PluginServerService } from '~/types'import { MetricsIngestionConsumerConfig } from './config'+import { recordMetricsIngested } from './ingestion-otel-metrics'import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT, MetricsDlqOutput, MetricsOutput } from './outputs/outputs'import { MetricsRateLimiterService } from './services/metrics-rate-limiter.service'import { MetricsIngestionMessage } from './types'@@ -304,6 +305,9 @@ export class MetricsIngestionConsumer {},},])+ // Only after the ClickHouse-bound produce resolves — messages that+ // fail and route to the DLQ must not count as ingested.+ recordMetricsIngested(message.teamId, message.bytesUncompressed, message.recordCount)} catch (error) {await this.produceToDlq(message, error)throw error