: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): pro-rate billing for rows removed by drop rules (#62580)
Daniel Visca0a54054a8b20
diff --git a/nodejs/src/logs-ingestion/config.ts b/nodejs/src/logs-ingestion/config.tsindex 068a9ceed805..877db53dde8d 100644--- a/nodejs/src/logs-ingestion/config.ts+++ b/nodejs/src/logs-ingestion/config.ts@@ -49,6 +49,13 @@ export type LogsIngestionConsumerConfig = {LOGS_SAMPLING_ENABLED_TEAMS: string/** When `true`, sampling always keeps every record (metrics path may still run). */LOGS_SAMPLING_KILLSWITCH: boolean+ /**+ * When `true`, rows removed by drop rules are credited back to the billed usage metrics+ * (`bytes_ingested` / `records_ingested`). When `false` (default), the credit is only+ * computed and observable via the `logs_ingestion_billing_*_credited_total` counters+ * (shadow mode) — billing is unchanged.+ */+ LOGS_BILLING_PRORATE_ENABLED: booleanREDIS_URL: stringREDIS_POOL_MIN_SIZE: numberREDIS_POOL_MAX_SIZE: number@@ -75,6 +82,7 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCoLOGS_LIMITER_TEAM_REFILL_RATE_KB_PER_SECOND: '',LOGS_SAMPLING_ENABLED_TEAMS: '*',LOGS_SAMPLING_KILLSWITCH: false,+ LOGS_BILLING_PRORATE_ENABLED: false,// Overlapping fields with CommonConfig, included for standalone usage// ok to connect to localhost over plaintext// nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transportdiff --git a/nodejs/src/logs-ingestion/logs-billing.test.ts b/nodejs/src/logs-ingestion/logs-billing.test.tsnew file mode 100644index 000000000000..8fb29d1ece91--- /dev/null+++ b/nodejs/src/logs-ingestion/logs-billing.test.ts@@ -0,0 +1,31 @@+import { billingByteReductionForDrops } from './logs-ingestion-consumer'++describe('billingByteReductionForDrops', () => {+ it.each<[string, number, number, number, number]>([+ // label, headerBytes, bytesDropped, bytesTotal, expected+ ['credits the dropped content fraction of the header', 1000, 600, 1000, 600],+ ['credits nothing when no rows were dropped', 1000, 0, 1000, 0],+ ['credits the full header when every row is dropped', 1000, 1000, 1000, 1000],+ ['credits nothing when bytesTotal is zero (unmeasurable)', 1000, 50, 0, 0],+ ['credits nothing when headerBytes is zero (unmeasurable)', 0, 50, 100, 0],+ ['caps the dropped fraction at 1 (defensive)', 1000, 1500, 1000, 1000],+ ['rounds to whole bytes (1000 × 1/3 = 333.33 → 333)', 1000, 1, 3, 333],+ ])('%s', (_label, headerBytes, bytesDropped, bytesTotal, expected) => {+ expect(billingByteReductionForDrops(headerBytes, bytesDropped, bytesTotal)).toBe(expected)+ })++ it('content- and record-weighted credits diverge on size-skewed drops (Tier 2 confidence signal)', () => {+ // header 10000; the dropped rows are 90% of content but only 10% of records (big rows dropped).+ const header = 10000+ const contentCredit = billingByteReductionForDrops(header, 9000, 10000) // 9000+ const recordCredit = billingByteReductionForDrops(header, 1, 10) // 1000+ // Large divergence ⇒ skewed batch ⇒ the content-weighted pro-rate is low-confidence.+ expect(Math.abs(contentCredit - recordCredit) / header).toBeGreaterThan(0.5)+ })++ it('content- and record-weighted credits agree on uniform drops (high confidence)', () => {+ const header = 10000+ // Uniform rows: dropping half the content == dropping half the records.+ expect(billingByteReductionForDrops(header, 5000, 10000)).toBe(billingByteReductionForDrops(header, 5, 10))+ })+})diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.tsindex 0c753e49765f..c6e57c5a8863 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.test.ts@@ -23,6 +23,7 @@ import {type LogsIngestionConsumerDeps,logMessageDlqCounter,logMessageDroppedCounter,+ logsBillingBytesCreditedCounter,logsBytesAllowedCounter,logsBytesDroppedCounter,logsBytesReceivedCounter,@@ -1573,9 +1574,11 @@ describe('LogsIngestionConsumer', () => {})describe('sampling usage to app_metrics2', () => {+ let mockSamplingCache: Pick<SamplingRulesCache, 'getCompiledRuleSet'>+beforeEach(async () => {await consumer.stop()- const mockSamplingCache: Pick<SamplingRulesCache, 'getCompiledRuleSet'> = {+ mockSamplingCache = {getCompiledRuleSet: (teamId: number) =>Promise.resolve(teamId === team.id@@ -1626,6 +1629,60 @@ describe('LogsIngestionConsumer', () => {expect(byRule).toBeDefined()expect(parseMetricValue(byRule!.value).count).toBe(1)})++ const sendDroppedAndKeptMessages = async () => {+ // Two single-record messages: the info one is fully dropped by the rule+ // (credit = its whole 400-byte header), the error one is kept (600 bytes).+ const messages = [+ ...(await createKafkaMessages([createLogMessage({ level: 'info' })], {+ token: team.api_token,+ bytes_uncompressed: '400',+ record_count: '1',+ })),+ ...(await createKafkaMessages([createLogMessage({ level: 'error' })], {+ token: team.api_token,+ bytes_uncompressed: '600',+ record_count: '1',+ })),+ ]+ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))+ }++ const teamBytesIngested = (): number | undefined => {+ const m = getProducedKafkaMessages()+ .filter((m) => m.topic === KAFKA_APP_METRICS_2)+ .find((m) => {+ const value = parseMetricValue(m.value)+ return value.metric_name === 'bytes_ingested' && value.team_id === team.id+ })+ return m ? parseMetricValue(m.value).count : undefined+ }++ it('shadow mode (default): computes the drop credit but bills the full gross bytes', async () => {+ const creditSpy = jest.spyOn(logsBillingBytesCreditedCounter, 'inc')++ await sendDroppedAndKeptMessages()++ // The would-be credit is computed and observable...+ expect(creditSpy).toHaveBeenCalledWith({ team_id: team.id.toString() }, 400)+ // ...but billed usage is untouched: full gross of both messages.+ expect(teamBytesIngested()).toBe(1000)+ })++ it('credits dropped rows off bytes_ingested when LOGS_BILLING_PRORATE_ENABLED', async () => {+ await consumer.stop()+ consumer = await createLogsIngestionConsumer(+ hub,+ { LOGS_BILLING_PRORATE_ENABLED: true },+ { samplingRulesCache: mockSamplingCache as SamplingRulesCache }+ )+ await deleteKeysWithPrefix(consumer['redis'], BASE_REDIS_KEY)++ await sendDroppedAndKeptMessages()++ // The fully-dropped message's 400-byte header is credited; only the kept one bills.+ expect(teamBytesIngested()).toBe(600)+ })})})diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.tsindex 67313e2c934c..fd21c756ccd7 100644--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts@@ -1,7 +1,7 @@import { trace } from '@opentelemetry/api'import { Message } from 'node-rdkafka'import pLimit from 'p-limit'-import { Counter } from 'prom-client'+import { Counter, Histogram } from 'prom-client'import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'@@ -99,7 +99,7 @@ export const logsBytesReceivedCounter = new Counter({export const logsBytesAllowedCounter = new Counter({name: 'logs_ingestion_bytes_allowed_total',- help: 'Total uncompressed bytes allowed through quota and rate limiting',+ help: 'Total uncompressed bytes allowed through quota and rate limiting. Gross of the drop-rule billing credit: billed bytes_ingested = this − logs_ingestion_billing_bytes_credited_total.',})export const logsBytesAllowedRecordsCounter = new Counter({@@ -126,7 +126,7 @@ export const logsRecordsReceivedCounter = new Counter({export const logsRecordsAllowedCounter = new Counter({name: 'logs_ingestion_records_allowed_total',- help: 'Total log records allowed through quota and rate limiting',+ help: 'Total log records allowed through quota and rate limiting. Gross of the drop-rule billing credit: billed records_ingested = this − logs_ingestion_billing_records_credited_total.',})export const logsRecordsDroppedCounter = new Counter({@@ -147,6 +147,60 @@ export const logsBytesDroppedByRuleCounter = new Counter({labelNames: ['team_id'],})+// --- Billing impact of drop rules (Tier 1) ---+export const logsBillingBytesCreditedCounter = new Counter({+ name: 'logs_ingestion_billing_bytes_credited_total',+ help: 'Uncompressed header bytes credited back to billing for rows removed by drop rules (pro-rated).',+ labelNames: ['team_id'],+})++export const logsBillingRecordsCreditedCounter = new Counter({+ name: 'logs_ingestion_billing_records_credited_total',+ help: 'Records removed by drop rules and credited back to billing.',+ labelNames: ['team_id'],+})++// --- Pro-rate accuracy-confidence signals (Tier 2). No team_id label — kept low-cardinality. ---+export const logsBillingProrateDivergenceHistogram = new Histogram({+ name: 'logs_ingestion_billing_prorate_divergence',+ help: 'Per-message |content-weighted − record-weighted credit| / header. High = size-skewed batch = pro-rate less trustworthy.',+ buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.25, 0.5, 1],+})++export const logsDropBatchRowsHistogram = new Histogram({+ name: 'logs_ingestion_drop_batch_rows',+ help: 'Rows per batch for messages that had drop-rule drops; small batches carry larger pro-rate error.',+ buckets: [1, 2, 5, 10, 50, 100, 500, 1000, 5000],+})++export const logsDropFractionHistogram = new Histogram({+ name: 'logs_ingestion_drop_fraction',+ help: 'Fraction of a message content dropped by drop rules; extreme fractions carry larger pro-rate error.',+ buckets: [0.1, 0.25, 0.5, 0.75, 0.9, 0.99, 1],+})++/**+ * Pro-rate a message's billable uncompressed bytes by the fraction of its content that drop+ * rules removed. Billing is on the per-message header (whole-batch wire size), but drops are+ * decided per row (content bytes), so we scale the header down by the dropped content fraction+ * to bill only what survived.+ *+ * Weights are customer-content bytes per row (body + attributes + event_name) — NOT the per-row+ * `bytes_uncompressed` field, whose near-constant denormalization overhead (duplicated resource+ * attributes, server uuid) would skew the ratio toward record-count weighting. Content weights+ * track "share of what the customer sent"; residual error vs true wire share (protobuf framing,+ * per-batch resource blocks) is small and direction-neutral. The result is always ≤ the gross+ * header (droppedFraction ≤ 1), so a message is never billed above today's gross. Returns 0 when+ * we can't measure (no header or no content bytes), i.e. no credit rather than a wrong one.+ */+export function billingByteReductionForDrops(headerBytes: number, bytesDropped: number, bytesTotal: number): number {+ if (headerBytes <= 0 || bytesDropped <= 0 || bytesTotal <= 0) {+ return 0+ }+ const droppedFraction = Math.min(1, bytesDropped / bytesTotal)+ return Math.round(headerBytes * droppedFraction)+}+export class LogsIngestionConsumer {protected name = 'LogsIngestionConsumer'// Billing identity for quota enforcement and usage metering; overridden by subclasses (e.g. traces).@@ -159,6 +213,7 @@ export class LogsIngestionConsumer {private samplingService: LogsSamplingServiceprivate readonly samplingEnabledTeamsRaw: stringprivate readonly samplingKillswitch: boolean+ private readonly billingProrateEnabled: booleanprotected groupId: stringprotected topic: string@@ -201,6 +256,7 @@ export class LogsIngestionConsumer {this.samplingService = new LogsSamplingService(this.redis, mergedConfig.LOGS_LIMITER_TTL_SECONDS)this.samplingEnabledTeamsRaw = mergedConfig.LOGS_SAMPLING_ENABLED_TEAMSthis.samplingKillswitch = mergedConfig.LOGS_SAMPLING_KILLSWITCH+ this.billingProrateEnabled = mergedConfig.LOGS_BILLING_PRORATE_ENABLED}private isSamplingEvalEnabledForTeam(teamId: number): boolean {@@ -236,6 +292,8 @@ export class LogsIngestionConsumer {recordsDropped: numberrecordsDroppedByRuleId: Map<string, number>bytesDroppedByRuleId: Map<string, number>+ contentBytesDropped: number+ contentBytesTotal: number}| {outcome: 'sampling_all_dropped'@@ -243,6 +301,8 @@ export class LogsIngestionConsumer {recordsDropped: numberrecordsDroppedByRuleId: Map<string, number>bytesDroppedByRuleId: Map<string, number>+ contentBytesDropped: number+ contentBytesTotal: number}> {const samplingCache = this.deps.samplingRulesCache@@ -285,6 +345,8 @@ export class LogsIngestionConsumer {recordsDropped: sampled.recordsDropped,recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,bytesDroppedByRuleId: sampled.bytesDroppedByRuleId,+ contentBytesDropped: sampled.contentBytesDropped,+ contentBytesTotal: sampled.contentBytesTotal,}}return {@@ -294,9 +356,12 @@ export class LogsIngestionConsumer {recordsDropped: sampled.recordsDropped,recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,bytesDroppedByRuleId: sampled.bytesDroppedByRuleId,+ contentBytesDropped: sampled.contentBytesDropped,+ contentBytesTotal: sampled.contentBytesTotal,}}+ // Passthrough (sampling disabled / no rules): nothing dropped, so nothing to credit.const res = await processLogMessageBuffer(message.message.value!, logsSettings)return {outcome: 'produce',@@ -305,6 +370,8 @@ export class LogsIngestionConsumer {recordsDropped: 0,recordsDroppedByRuleId: new Map(),bytesDroppedByRuleId: new Map(),+ contentBytesDropped: 0,+ contentBytesTotal: 0,}}@@ -379,6 +446,7 @@ export class LogsIngestionConsumer {}logsBytesAllowedRecordsCounter.inc(totalBytesAllowedRecords)+ // Gross, before the drop-rule billing credit applied in processAndProduceLogMessages (see counter help).logsBytesAllowedCounter.inc(totalBytesAllowed)logsRecordsAllowedCounter.inc(totalRecordsAllowed)@@ -506,6 +574,59 @@ export class LogsIngestionConsumer {},async () => this.resolveLogMessageBufferWithOptionalSampling(message, logsSettings))++ // Drop rules removed rows from this message — credit billing by the dropped+ // content fraction. `bytesReceived` stays gross (what was sent); `bytesAllowed`+ // (→ bytes_ingested) and `recordsAllowed` reflect only what survived the drops.+ if (resolved.recordsDropped > 0) {+ const header = message.bytesUncompressed+ const contentCredit = billingByteReductionForDrops(+ header,+ resolved.contentBytesDropped,+ resolved.contentBytesTotal+ )+ // Second estimator (record-weighted) for the accuracy-confidence signal:+ // when content- and record-weighted credits diverge, the batch is size-skewed+ // and the content-weighted pro-rate we bill on is less trustworthy.+ const recordCredit = billingByteReductionForDrops(+ header,+ resolved.recordsDropped,+ message.recordCount+ )++ const teamIdLabel = message.teamId.toString()+ if (contentCredit > 0) {+ logsBillingBytesCreditedCounter.inc({ team_id: teamIdLabel }, contentCredit)+ }+ logsBillingRecordsCreditedCounter.inc({ team_id: teamIdLabel }, resolved.recordsDropped)+ if (message.recordCount > 0) {+ logsDropBatchRowsHistogram.observe(message.recordCount)+ }+ if (resolved.contentBytesTotal > 0) {+ logsDropFractionHistogram.observe(+ Math.min(1, resolved.contentBytesDropped / resolved.contentBytesTotal)+ )+ }+ if (header > 0) {+ logsBillingProrateDivergenceHistogram.observe(+ Math.abs(contentCredit - recordCredit) / header+ )+ }++ // Shadow mode unless LOGS_BILLING_PRORATE_ENABLED: the credit above is+ // computed and counted (observability) but billed usage is untouched.+ if (this.billingProrateEnabled) {+ const billingRow = usageStats.get(message.teamId)+ if (billingRow) {+ billingRow.bytesAllowed = Math.max(0, billingRow.bytesAllowed - contentCredit)+ billingRow.recordsAllowed = Math.max(+ 0,+ billingRow.recordsAllowed - resolved.recordsDropped+ )+ }+ }+ }+if (resolved.outcome === 'sampling_all_dropped') {logMessageDroppedCounter.inc({ reason: 'sampling_all_dropped', team_id: message.teamId.toString() },diff --git a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.tsindex bee35e7bc565..2dbf88a5eb47 100644--- a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts@@ -148,7 +148,7 @@ describe('LogsSamplingService', () => {const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', [baseLog('a', 'api', 300),baseLog('b', 'api', 400),- baseLog('c', 'api', 500),+ { ...baseLog('c', 'api', 500), attributes: { k: 'vv' }, event_name: 'evt' },])const mockRedis: RedisV2 = {@@ -168,6 +168,11 @@ describe('LogsSamplingService', () => {expect(result.recordsDroppedByRuleId.get('rl-kb')).toBe(1)expect(result.bytesDropped).toBe(500)expect(result.bytesDroppedByRuleId.get('rl-kb')).toBe(500)+ // Billing pro-rate weights are customer-content bytes (body + attributes + event_name),+ // independent of the per-row bytes_uncompressed field used for rate limiting:+ // rows a,b = body 'x' (1 each); dropped row c = body(1) + attrs 'k'+'vv'(3) + 'evt'(3) = 7.+ expect(result.contentBytesTotal).toBe(9)+ expect(result.contentBytesDropped).toBe(7)const [, , kept] = await decodeLogRecords(result.value)expect(kept).toHaveLength(2)@@ -208,6 +213,10 @@ describe('LogsSamplingService', () => {expect(result.recordsDropped).toBe(1)expect(result.bytesDropped).toBe(1000)expect(result.bytesDroppedByRuleId.get('rl-kb')).toBe(1000)+ // Content weights don't depend on the per-row bytes_uncompressed field at all:+ // the null-field row still weighs its body bytes (1 each, 3 rows, 1 dropped).+ expect(result.contentBytesTotal).toBe(3)+ expect(result.contentBytesDropped).toBe(1)const [, , kept] = await decodeLogRecords(result.value)expect(kept).toHaveLength(2)diff --git a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.tsindex ec61dc21aa2d..31e3856f21f7 100644--- a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts@@ -68,12 +68,32 @@ export type ProcessBufferWithSamplingResult = {bytesDropped: number/** Sum of per-row `bytes_uncompressed` for dropped lines, attributed to the first matching rule UUID. */bytesDroppedByRuleId: Map<string, number>+ /** Sum of customer-content bytes (body + attributes + event_name) for dropped lines. Billing pro-rate numerator. */+ contentBytesDropped: number+ /** Sum of customer-content bytes across ALL decoded rows (kept + dropped). Billing pro-rate denominator. */+ contentBytesTotal: number/** When true, the caller must not produce this message to downstream Kafka (all lines sampled out). */allDropped: boolean}const recordBytes = (r: LogRecord): number => r.bytes_uncompressed ?? 0+/**+ * Customer-sent content bytes of a row: body + attributes + event_name. The billing+ * pro-rate weight — deliberately NOT `bytes_uncompressed`, which includes per-row+ * denormalization overhead (resource attributes duplicated onto every row, server+ * uuid, id placeholders). That overhead is near-constant per row, so as a ratio+ * weight it would skew the pro-rate toward record-count weighting instead of+ * "share of what the customer sent".+ */+const contentBytes = (r: LogRecord): number => {+ let total = Buffer.byteLength(r.body ?? '') + Buffer.byteLength(r.event_name ?? '')+ for (const [k, v] of Object.entries(r.attributes ?? {})) {+ total += Buffer.byteLength(k) + Buffer.byteLength(v ?? '')+ }+ return total+}+export class LogsSamplingService {private rateLimiter: KeyedRateLimiterService@@ -102,6 +122,8 @@ export class LogsSamplingService {const recordsDroppedByRuleId = new Map<string, number>()let bytesDropped = 0const bytesDroppedByRuleId = new Map<string, number>()+ let contentBytesDropped = 0+ const contentBytesTotal = records.reduce((sum, r) => sum + contentBytes(r), 0)const useRate = Boolean(ruleSet.hasRateLimitRules && teamId != null)@@ -126,6 +148,7 @@ export class LogsSamplingService {const rb = recordBytes(record)recordsDropped++bytesDropped += rb+ contentBytesDropped += contentBytes(record)recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)bytesDroppedByRuleId.set(c.ruleId, (bytesDroppedByRuleId.get(c.ruleId) ?? 0) + rb)continue@@ -137,6 +160,7 @@ export class LogsSamplingService {const rb = recordBytes(record)recordsDropped++bytesDropped += rb+ contentBytesDropped += contentBytes(record)if (c.ruleId != null) {recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)bytesDroppedByRuleId.set(c.ruleId, (bytesDroppedByRuleId.get(c.ruleId) ?? 0) + rb)@@ -152,6 +176,7 @@ export class LogsSamplingService {const rb = recordBytes(record)recordsDropped++bytesDropped += rb+ contentBytesDropped += contentBytes(record)if (ruleId != null) {recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)bytesDroppedByRuleId.set(ruleId, (bytesDroppedByRuleId.get(ruleId) ?? 0) + rb)@@ -179,6 +204,8 @@ export class LogsSamplingService {recordsDroppedByRuleId,bytesDropped,bytesDroppedByRuleId,+ contentBytesDropped,+ contentBytesTotal,allDropped: true,}}@@ -190,6 +217,8 @@ export class LogsSamplingService {recordsDroppedByRuleId,bytesDropped,bytesDroppedByRuleId,+ contentBytesDropped,+ contentBytesTotal,allDropped: false,}}