Skip to content

: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.

feat(metrics): default the retention-days header to 30 days (#103065)

Frank Hamandf90a8ae3a808
diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.ts
new file mode 100644
index 000000000000..c189bc38853e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.test.ts
@@ -0,0 +1,108 @@
+import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'
+
+import { Message } from 'node-rdkafka'
+
+import {
+ KAFKA_APP_METRICS_2,
+ KAFKA_METRICS_CLICKHOUSE,
+ KAFKA_METRICS_INGESTION_DLQ,
+} from '~/common/config/kafka-topics'
+import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'
+import { closeHub, createHub } from '~/common/utils/db/hub'
+import { createTestTeamFixture } from '~/tests/helpers/sql'
+import { Hub, Team } from '~/types'
+
+import { getDefaultMetricsIngestionConsumerConfig } from './config'
+import { DEFAULT_METRICS_RETENTION_DAYS, MetricsIngestionConsumer } from './metrics-ingestion-consumer'
+import { METRICS_DLQ_OUTPUT, METRICS_OUTPUT, MetricsDlqOutput, MetricsOutput } from './outputs/outputs'
+
+const createKafkaMessage = (headers: Record<string, string>): Message => {
+ // The consumer passes the Avro payload through without decoding it.
+ const value = Buffer.from('avro-payload')
+ return {
+ key: null,
+ value,
+ size: value.length,
+ topic: 'test',
+ offset: 0,
+ timestamp: Date.now(),
+ partition: 1,
+ headers: Object.entries(headers).map(([key, headerValue]) => ({ [key]: Buffer.from(headerValue) })),
+ }
+}
+
+describe('MetricsIngestionConsumer', () => {
+ let consumer: MetricsIngestionConsumer
+ let hub: Hub
+ let team: Team
+
+ beforeEach(async () => {
+ hub = await createHub()
+ team = (await createTestTeamFixture(hub.postgres)).team
+
+ consumer = new MetricsIngestionConsumer(getDefaultMetricsIngestionConsumerConfig(), {
+ teamManager: hub.teamManager,
+ quotaLimiting: hub.quotaLimiting,
+ outputs: new IngestionOutputs<MetricsOutput | MetricsDlqOutput | AppMetricsOutput>({
+ [APP_METRICS_OUTPUT]: new SingleIngestionOutput(
+ APP_METRICS_OUTPUT,
+ KAFKA_APP_METRICS_2,
+ mockProducer,
+ 'test'
+ ),
+ [METRICS_OUTPUT]: new SingleIngestionOutput(
+ METRICS_OUTPUT,
+ KAFKA_METRICS_CLICKHOUSE,
+ mockProducer,
+ 'test'
+ ),
+ [METRICS_DLQ_OUTPUT]: new SingleIngestionOutput(
+ METRICS_DLQ_OUTPUT,
+ KAFKA_METRICS_INGESTION_DLQ,
+ mockProducer,
+ 'test'
+ ),
+ }),
+ })
+ // NOTE: We don't actually use kafka so we skip instantiation for faster tests
+ consumer['kafkaConsumer'] = {
+ connect: jest.fn(),
+ disconnect: jest.fn(),
+ isHealthy: jest.fn().mockReturnValue({ status: 'healthy' }),
+ } as any
+ await consumer.start()
+
+ jest.spyOn(hub.quotaLimiting, 'isTeamTokenQuotaLimited').mockResolvedValue(false)
+ })
+
+ afterEach(async () => {
+ await consumer.stop()
+ await closeHub(hub)
+ })
+
+ it('stamps the default retention-days header on messages produced to ClickHouse', async () => {
+ const message = createKafkaMessage({
+ token: team.api_token,
+ bytes_uncompressed: '100',
+ record_count: '1',
+ })
+
+ const { backgroundTask } = await consumer.processKafkaBatch([message])
+ await backgroundTask
+
+ const produced = mockProducerObserver
+ .getProducedMessages()
+ .filter((batch) => batch.topic === KAFKA_METRICS_CLICKHOUSE)
+ expect(produced).toHaveLength(1)
+ expect(produced[0].messages).toHaveLength(1)
+ expect(produced[0].messages[0].headers).toEqual(
+ expect.objectContaining({
+ token: team.api_token,
+ team_id: team.id.toString(),
+ 'retention-days': DEFAULT_METRICS_RETENTION_DAYS.toString(),
+ })
+ )
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts
index da4978a13860..7ec9b02a03ca 100644
--- a/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/metrics/metrics-ingestion-consumer.ts
@@ -51,6 +51,9 @@ const DEFAULT_USAGE_STATS: UsageStats = {
export type UsageStatsByTeam = Map<number, UsageStats>
+/** Retention stamped on every produced batch; metrics has no per-team setting yet. ClickHouse falls back to `DEFAULT_RETENTION_DAYS` in `posthog/clickhouse/metrics/metrics2.py` only when this header is absent. */
+export const DEFAULT_METRICS_RETENTION_DAYS = 30
+
export const metricMessageDroppedCounter = new Counter({
name: 'metrics_ingestion_message_dropped_count',
help: 'The number of metrics ingestion messages dropped',
@@ -302,6 +305,7 @@ export class MetricsIngestionConsumer {
...parseKafkaHeaders(message.message.headers),
token: message.token,
team_id: message.teamId.toString(),
+ 'retention-days': DEFAULT_METRICS_RETENTION_DAYS.toString(),
},
},
])
diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.py
index 529aba91e81d..d7b960cf0e84 100644
--- a/products/metrics/backend/metric_names_query_runner.py
+++ b/products/metrics/backend/metric_names_query_runner.py
@@ -49,11 +49,6 @@ _SPARKLINE_QUERY_SETTINGS = HogQLGlobalSettings(
read_overflow_mode="throw",
)
-# Both `metric_series` and `metrics` expire at the same `original_expiry_timestamp`,
-# which ingest sets to the team's retention (90 days by default).
-# A lookback beyond this would quietly return fewer names than the raw table has.
-SERIES_RETENTION = dt.timedelta(days=90)
-
# Short enough that a new metric shows up while someone is still wiring it up,
# long enough to absorb the burst of mounts a team generates in a working session.
METRIC_NAMES_CACHE_TTL = 60