: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(logs): emit bytes_ingested_records usage metric for billing comparison (#63115)
Daniel Viscafa671faf33b0
diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.tsindex 276f0036df40..0c753e49765f 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts@@ -27,6 +27,7 @@ import {logsBytesDroppedCounter,logsBytesReceivedCounter,logsRecordsAllowedCounter,+ logsRecordsBytesExceedPayloadCounter,logsRecordsDroppedCounter,logsRecordsReceivedCounter,} from './logs-ingestion-consumer'@@ -968,6 +969,49 @@ describe('LogsIngestionConsumer', () => {expect(team2BytesReceived?.value.count).toBe(200)expect(team2BytesIngested?.value.count).toBe(200)})++ it('should emit bytes_ingested_records from the bytes_uncompressed_records header', async () => {+ const messages = await createKafkaMessages([createLogMessage()], {+ token: team.api_token,+ bytes_uncompressed: '1024',+ bytes_uncompressed_records: '900',+ record_count: '5',+ })++ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))++ const appMetricsMessages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ const bytesIngested = appMetricsMessages.find((m) => m.value.metric_name === 'bytes_ingested')+ const bytesIngestedRecords = appMetricsMessages.find(+ (m) => m.value.metric_name === 'bytes_ingested_records'+ )+ expect(bytesIngested?.value.count).toBe(1024)+ expect(bytesIngestedRecords?.value.count).toBe(900)+ })++ it('should flag and still emit when bytes_uncompressed_records exceeds bytes_uncompressed', async () => {+ const exceedCounterSpy = jest.spyOn(logsRecordsBytesExceedPayloadCounter, 'inc')+ const messages = await createKafkaMessages([createLogMessage()], {+ token: team.api_token,+ bytes_uncompressed: '1024',+ bytes_uncompressed_records: '1500',+ record_count: '5',+ })++ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))++ expect(exceedCounterSpy).toHaveBeenCalledWith({ team_id: team.id.toString() })++ // The comparison metric is emitted as-is, even above the payload size —+ // it exists precisely to surface this case.+ const appMetricsMessages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ const bytesIngested = appMetricsMessages.find((m) => m.value.metric_name === 'bytes_ingested')+ const bytesIngestedRecords = appMetricsMessages.find(+ (m) => m.value.metric_name === 'bytes_ingested_records'+ )+ expect(bytesIngested?.value.count).toBe(1024)+ expect(bytesIngestedRecords?.value.count).toBe(1500)+ })})describe('trackOutgoingTrafficAndBuildUsageStats', () => {@@ -993,6 +1037,29 @@ describe('LogsIngestionConsumer', () => {expect(stats!.piiReplacements).toBe(0)})+ it('should sum bytesAllowedRecords and treat a missing header as zero', async () => {+ const messages = [+ ...(await createKafkaMessages([createLogMessage()], {+ token: team.api_token,+ bytes_uncompressed: '100',+ bytes_uncompressed_records: '80',+ record_count: '1',+ })),+ ...(await createKafkaMessages([createLogMessage()], {+ token: team.api_token,+ bytes_uncompressed: '200',+ record_count: '2',+ })),+ ]++ const parsed = await consumer['_parseKafkaBatch'](messages)+ const usageStats = consumer['trackOutgoingTrafficAndBuildUsageStats'](parsed, [])++ const stats = usageStats.get(team.id)+ expect(stats!.bytesAllowed).toBe(300)+ expect(stats!.bytesAllowedRecords).toBe(80)+ })+it('should aggregate stats for multiple messages from same team', async () => {const messages = [...(await createKafkaMessages([createLogMessage()], {@@ -1133,6 +1200,7 @@ describe('LogsIngestionConsumer', () => {recordsReceived: 10,bytesAllowed: 800,recordsAllowed: 8,+ bytesAllowedRecords: 700,bytesDropped: 200,recordsDropped: 2,piiReplacements: 0,@@ -1145,12 +1213,13 @@ describe('LogsIngestionConsumer', () => {const messages = getProducedKafkaMessages().filter((m) => m.topic === KAFKA_APP_METRICS_2)- expect(messages).toHaveLength(7)+ expect(messages).toHaveLength(8)const metricNames = messages.map((m) => parseMetricValue(m.value)?.metric_name)expect(metricNames).toContain('bytes_received')expect(metricNames).toContain('records_received')expect(metricNames).toContain('bytes_ingested')+ expect(metricNames).toContain('bytes_ingested_records')expect(metricNames).toContain('records_ingested')expect(metricNames).toContain('bytes_dropped')expect(metricNames).toContain('records_dropped')@@ -1172,6 +1241,7 @@ describe('LogsIngestionConsumer', () => {recordsReceived: 5,bytesAllowed: 500,recordsAllowed: 5,+ bytesAllowedRecords: 0,bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,@@ -1204,6 +1274,7 @@ describe('LogsIngestionConsumer', () => {recordsReceived: 10,bytesAllowed: 1000,recordsAllowed: 10,+ bytesAllowedRecords: 0,bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,@@ -1243,6 +1314,7 @@ describe('LogsIngestionConsumer', () => {recordsReceived: 1,bytesAllowed: 100,recordsAllowed: 1,+ bytesAllowedRecords: 0,bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,@@ -1256,6 +1328,7 @@ describe('LogsIngestionConsumer', () => {recordsReceived: 2,bytesAllowed: 200,recordsAllowed: 2,+ bytesAllowedRecords: 0,bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.tsindex 28486025e1fb..67313e2c934c 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts@@ -55,6 +55,8 @@ export type UsageStats = {recordsReceived: numberbytesAllowed: numberrecordsAllowed: number+ /** Sum of per-record content sizes for allowed batches — billing comparison candidate for bytesAllowed. */+ bytesAllowedRecords: numberbytesDropped: numberrecordsDropped: numberpiiReplacements: number@@ -66,6 +68,7 @@ const DEFAULT_USAGE_STATS: UsageStats = {recordsReceived: 0,bytesAllowed: 0,recordsAllowed: 0,+ bytesAllowedRecords: 0,bytesDropped: 0,recordsDropped: 0,piiReplacements: 0,@@ -99,6 +102,17 @@ export const logsBytesAllowedCounter = new Counter({help: 'Total uncompressed bytes allowed through quota and rate limiting',})+export const logsBytesAllowedRecordsCounter = new Counter({+ name: 'logs_ingestion_bytes_allowed_records_total',+ help: 'Records-based uncompressed bytes (sum of per-record sizes) allowed through quota and rate limiting',+})++export const logsRecordsBytesExceedPayloadCounter = new Counter({+ name: 'logs_ingestion_records_bytes_exceed_payload_total',+ help: 'Batches where the records-based bytes sum exceeded the payload-based bytes_uncompressed header',+ labelNames: ['team_id'],+})+export const logsBytesDroppedCounter = new Counter({name: 'logs_ingestion_bytes_dropped_total',help: 'Total uncompressed bytes dropped due to quota or rate limiting',@@ -349,18 +363,22 @@ export class LogsIngestionConsumer {let totalRecordsAllowed = 0const usageStats: UsageStatsByTeam = new Map()+ let totalBytesAllowedRecords = 0for (const message of allowedMessages) {const stats = usageStats.get(message.teamId) || { ...DEFAULT_USAGE_STATS }stats.bytesReceived += message.bytesUncompressedstats.recordsReceived += message.recordCountstats.bytesAllowed += message.bytesUncompressedstats.recordsAllowed += message.recordCount+ stats.bytesAllowedRecords += message.bytesUncompressedRecordsusageStats.set(message.teamId, stats)totalBytesAllowed += message.bytesUncompressed+ totalBytesAllowedRecords += message.bytesUncompressedRecordstotalRecordsAllowed += message.recordCount}+ logsBytesAllowedRecordsCounter.inc(totalBytesAllowedRecords)logsBytesAllowedCounter.inc(totalBytesAllowed)logsRecordsAllowedCounter.inc(totalRecordsAllowed)@@ -568,6 +586,10 @@ export class LogsIngestionConsumer {this.queueUsageMetric(teamId, 'bytes_received', stats.bytesReceived)this.queueUsageMetric(teamId, 'records_received', stats.recordsReceived)this.queueUsageMetric(teamId, 'bytes_ingested', stats.bytesAllowed)+ // Records-based counterpart to `bytes_ingested` (sum of per-record sizes instead of+ // payload size). Emitted in parallel so the two can be compared before billing+ // switches to the records-based value; not yet read by usage reports.+ this.queueUsageMetric(teamId, 'bytes_ingested_records', stats.bytesAllowedRecords)this.queueUsageMetric(teamId, 'records_ingested', stats.recordsAllowed)this.queueUsageMetric(teamId, 'bytes_dropped', stats.bytesDropped)this.queueUsageMetric(teamId, 'records_dropped', stats.recordsDropped)@@ -681,14 +703,22 @@ export class LogsIngestionConsumer {}const bytesUncompressed = parseInt(headers.bytes_uncompressed ?? '0', 10)+ const bytesUncompressedRecords = parseInt(headers.bytes_uncompressed_records ?? '0', 10)const bytesCompressed = parseInt(headers.bytes_compressed ?? '0', 10)const recordCount = parseInt(headers.record_count ?? '0', 10)+ if (bytesUncompressedRecords > bytesUncompressed) {+ // Billing can only switch from payload-based to records-based bytes if the+ // records sum never exceeds the payload size — flag any violation.+ logsRecordsBytesExceedPayloadCounter.inc({ team_id: team.id.toString() })+ }+events.push({token,message,teamId: team.id,bytesUncompressed,+ bytesUncompressedRecords,bytesCompressed,recordCount,})diff --git a/nodejs/src/logs-ingestion/types.ts b/nodejs/src/logs-ingestion/types.tsindex 1adf7052b977..5636aba204e3 100644--- a/nodejs/src/logs-ingestion/types.ts+++ b/nodejs/src/logs-ingestion/types.ts@@ -5,6 +5,8 @@ export type LogsIngestionMessage = {teamId: numbermessage: MessagebytesUncompressed: number+ /** Sum of per-record content sizes from the `bytes_uncompressed_records` header; 0 for batches from older producers. */+ bytesUncompressedRecords: numberbytesCompressed: numberrecordCount: number}