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(logs-ingestion): emit bytes_dropped_by_rule to app_metrics2 (#59499)

Daniel Visca60136c72862d
diff --git a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
index 9d07ac1cb99e..e9c7f513c173 100644
--- a/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs-ingestion/logs-ingestion-consumer.ts
@@ -118,6 +118,12 @@ export const logsSamplingRecordsDroppedCounter = new Counter({
labelNames: ['team_id'],
})
+export const logsBytesDroppedByRuleCounter = new Counter({
+ name: 'logs_ingestion_bytes_dropped_by_rule_total',
+ help: 'Bytes dropped by drop rules, summed from per-row bytes_uncompressed.',
+ labelNames: ['team_id'],
+})
+
export class LogsIngestionConsumer {
protected name = 'LogsIngestionConsumer'
protected kafkaConsumer: KafkaConsumerInterface
@@ -197,12 +203,14 @@ export class LogsIngestionConsumer {
pii: PiiScrubStats
recordsDropped: number
recordsDroppedByRuleId: Map<string, number>
+ bytesDroppedByRuleId: Map<string, number>
}
| {
outcome: 'sampling_all_dropped'
pii: PiiScrubStats
recordsDropped: number
recordsDroppedByRuleId: Map<string, number>
+ bytesDroppedByRuleId: Map<string, number>
}
> {
const samplingCache = this.deps.samplingRulesCache
@@ -235,12 +243,16 @@ export class LogsIngestionConsumer {
if (sampled.recordsDropped > 0) {
logsSamplingRecordsDroppedCounter.inc({ team_id: message.teamId.toString() }, sampled.recordsDropped)
}
+ if (sampled.bytesDropped > 0) {
+ logsBytesDroppedByRuleCounter.inc({ team_id: message.teamId.toString() }, sampled.bytesDropped)
+ }
if (sampled.allDropped) {
return {
outcome: 'sampling_all_dropped',
pii: sampled.pii,
recordsDropped: sampled.recordsDropped,
recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,
+ bytesDroppedByRuleId: sampled.bytesDroppedByRuleId,
}
}
return {
@@ -249,6 +261,7 @@ export class LogsIngestionConsumer {
pii: sampled.pii,
recordsDropped: sampled.recordsDropped,
recordsDroppedByRuleId: sampled.recordsDroppedByRuleId,
+ bytesDroppedByRuleId: sampled.bytesDroppedByRuleId,
}
}
@@ -259,6 +272,7 @@ export class LogsIngestionConsumer {
pii: res.pii,
recordsDropped: 0,
recordsDroppedByRuleId: new Map(),
+ bytesDroppedByRuleId: new Map(),
}
}
@@ -457,11 +471,13 @@ export class LogsIngestionConsumer {
)
this.addPiiStatsIntoUsage(usageStats, message.teamId, resolved.pii)
this.queueSamplingRecordsDroppedByRule(message.teamId, resolved.recordsDroppedByRuleId)
+ this.queueBytesDroppedByRule(message.teamId, resolved.bytesDroppedByRuleId)
return Promise.resolve()
}
- const { processedValue, pii, recordsDroppedByRuleId } = resolved
+ const { processedValue, pii, recordsDroppedByRuleId, bytesDroppedByRuleId } = resolved
this.addPiiStatsIntoUsage(usageStats, message.teamId, pii)
this.queueSamplingRecordsDroppedByRule(message.teamId, recordsDroppedByRuleId)
+ this.queueBytesDroppedByRule(message.teamId, bytesDroppedByRuleId)
// Await so a rejection here lands in the catch and routes to the DLQ.
await this.deps.outputs.queueMessages(LOGS_OUTPUT, [
@@ -578,6 +594,27 @@ export class LogsIngestionConsumer {
}
}
+ /**
+ * Per-rule dropped bytes in app_metrics2 (`bytes_dropped_by_rule`). Summed from per-row
+ * `bytes_uncompressed`; bridges drop-rule accounting toward billing's `bytes_ingested`.
+ */
+ private queueBytesDroppedByRule(teamId: number, byRule: Map<string, number>): void {
+ for (const [ruleId, count] of byRule) {
+ if (count <= 0) {
+ continue
+ }
+ this.appMetricsAggregator.queue({
+ team_id: teamId,
+ app_source: 'logs',
+ app_source_id: '',
+ instance_id: ruleId,
+ metric_kind: 'usage',
+ metric_name: 'bytes_dropped_by_rule',
+ count,
+ })
+ }
+ }
+
@instrumented('logsIngestionConsumer.handleEachBatch.parseKafkaMessages')
public async _parseKafkaBatch(messages: Message[]): Promise<LogsIngestionMessage[]> {
const events: LogsIngestionMessage[] = []
diff --git a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts
index 6a8ac7961d22..3bd0ae99737b 100644
--- a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts
+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.test.ts
@@ -25,12 +25,13 @@ const LOG_RECORD_AVRO = avro.Type.forSchema({
{ name: 'instrumentation_scope', type: ['null', 'string'] },
{ name: 'event_name', type: ['null', 'string'] },
{ name: 'attributes', type: ['null', { type: 'map', values: 'string' }] },
+ { name: 'bytes_uncompressed', type: ['null', 'long'] },
],
})
const logsSettings: LogsSettings = { json_parse_logs: false, pii_scrub_logs: false }
-function baseLog(uuid: string, serviceName: string): LogRecord {
+function baseLog(uuid: string, serviceName: string, bytesUncompressed: number | null = null): LogRecord {
return {
uuid,
trace_id: null,
@@ -46,6 +47,7 @@ function baseLog(uuid: string, serviceName: string): LogRecord {
instrumentation_scope: null,
event_name: null,
attributes: null,
+ bytes_uncompressed: bytesUncompressed,
}
}
@@ -62,9 +64,9 @@ describe('LogsSamplingService', () => {
},
])
const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', [
- baseLog('a', 'api'),
- baseLog('b', 'api'),
- baseLog('c', 'api'),
+ baseLog('a', 'api', 100),
+ baseLog('b', 'api', 100),
+ baseLog('c', 'api', 100),
])
const mockRedis: RedisV2 = {
@@ -82,12 +84,54 @@ describe('LogsSamplingService', () => {
expect(result.recordsDropped).toBe(1)
expect(result.recordsDroppedByRuleId.get('rl-1')).toBe(1)
+ // Each row is fixtured at 100 bytes; the one dropped row contributes 100.
+ expect(result.bytesDropped).toBe(100)
+ expect(result.bytesDroppedByRuleId.get('rl-1')).toBe(100)
expect(result.allDropped).toBe(false)
const [, , kept] = await decodeLogRecords(result.value)
expect(kept).toHaveLength(2)
})
+ it('attributes per-row bytes to the dropping rule and contributes 0 for null bytes_uncompressed', async () => {
+ const ruleSet = compileRuleSet([
+ {
+ id: 'rl-1',
+ rule_type: 'rate_limit',
+ scope_service: 'api',
+ scope_path_pattern: null,
+ scope_attribute_filters: [],
+ config: { logs_per_second: 100, burst_logs: 1000 },
+ },
+ ])
+ // 3 rows: 250 bytes, 750 bytes, null (old-producer message).
+ // Token budget of 1 → first row admitted, the other two dropped.
+ const buffer = await encodeLogRecords(LOG_RECORD_AVRO, 'zstandard', [
+ baseLog('a', 'api', 250),
+ baseLog('b', 'api', 750),
+ baseLog('c', 'api', null),
+ ])
+
+ const mockRedis: RedisV2 = {
+ useClient: jest.fn(() => Promise.resolve(null)),
+ usePipeline: jest.fn((_opts, cb) => {
+ const pipeline = { checkRateLimitV2: jest.fn() } as unknown as RedisClientPipeline
+ cb(pipeline)
+ const pipelineResult: [Error | null, any][] = [[null, [1, 0] as const]]
+ return Promise.resolve(pipelineResult)
+ }),
+ }
+
+ const service = new LogsSamplingService(mockRedis, 60)
+ const result = await service.processBuffer(buffer, logsSettings, ruleSet, 99)
+
+ expect(result.recordsDropped).toBe(2)
+ // Only the row with a populated bytes_uncompressed contributes to the byte sum;
+ // the null row falls back to 0 (in-flight transition behavior).
+ expect(result.bytesDropped).toBe(750)
+ expect(result.bytesDroppedByRuleId.get('rl-1')).toBe(750)
+ })
+
it('fail-open keeps all rate_limit lines when Redis pipeline returns null', async () => {
const ruleSet = compileRuleSet([
{
@@ -111,6 +155,8 @@ describe('LogsSamplingService', () => {
expect(result.recordsDropped).toBe(0)
expect(result.recordsDroppedByRuleId.size).toBe(0)
+ expect(result.bytesDropped).toBe(0)
+ expect(result.bytesDroppedByRuleId.size).toBe(0)
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.ts
index b06a83eb8dbb..92ce4bfaad3f 100644
--- a/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts
+++ b/nodejs/src/logs-ingestion/sampling/logs-sampling.service.ts
@@ -64,10 +64,16 @@ export type ProcessBufferWithSamplingResult = {
recordsDropped: number
/** Counts dropped lines (drop / sample_dropped) attributed to the first matching rule UUID. */
recordsDroppedByRuleId: Map<string, number>
+ /** Sum of per-row `bytes_uncompressed` for dropped lines. Rows from old producers contribute 0. */
+ bytesDropped: number
+ /** Sum of per-row `bytes_uncompressed` for dropped lines, attributed to the first matching rule UUID. */
+ bytesDroppedByRuleId: Map<string, 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
+
export class LogsSamplingService {
private rateLimiter: KeyedRateLimiterService
@@ -94,6 +100,8 @@ export class LogsSamplingService {
const kept: LogRecord[] = []
let recordsDropped = 0
const recordsDroppedByRuleId = new Map<string, number>()
+ let bytesDropped = 0
+ const bytesDroppedByRuleId = new Map<string, number>()
const useRate = Boolean(ruleSet.hasRateLimitRules && teamId != null)
@@ -115,17 +123,23 @@ export class LogsSamplingService {
const c = classifications[i]!
if (c.kind === 'rate_limit') {
if (rateKeep.get(i) === false) {
+ const rb = recordBytes(record)
recordsDropped++
+ bytesDropped += rb
recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)
+ bytesDroppedByRuleId.set(c.ruleId, (bytesDroppedByRuleId.get(c.ruleId) ?? 0) + rb)
continue
}
kept.push(record)
continue
}
if (c.decision === SAMPLING_DECISION_DROP || c.decision === SAMPLING_DECISION_SAMPLE_DROPPED) {
+ const rb = recordBytes(record)
recordsDropped++
+ bytesDropped += rb
if (c.ruleId != null) {
recordsDroppedByRuleId.set(c.ruleId, (recordsDroppedByRuleId.get(c.ruleId) ?? 0) + 1)
+ bytesDroppedByRuleId.set(c.ruleId, (bytesDroppedByRuleId.get(c.ruleId) ?? 0) + rb)
}
continue
}
@@ -135,9 +149,12 @@ export class LogsSamplingService {
for (const record of records) {
const { decision, ruleId } = safeEvaluateLogRecord(ruleSet, record, teamId ?? 0)
if (decision === SAMPLING_DECISION_DROP || decision === SAMPLING_DECISION_SAMPLE_DROPPED) {
+ const rb = recordBytes(record)
recordsDropped++
+ bytesDropped += rb
if (ruleId != null) {
recordsDroppedByRuleId.set(ruleId, (recordsDroppedByRuleId.get(ruleId) ?? 0) + 1)
+ bytesDroppedByRuleId.set(ruleId, (bytesDroppedByRuleId.get(ruleId) ?? 0) + rb)
}
continue
}
@@ -155,10 +172,26 @@ export class LogsSamplingService {
})
if (kept.length === 0) {
- return { value: Buffer.alloc(0), pii, recordsDropped, recordsDroppedByRuleId, allDropped: true }
+ return {
+ value: Buffer.alloc(0),
+ pii,
+ recordsDropped,
+ recordsDroppedByRuleId,
+ bytesDropped,
+ bytesDroppedByRuleId,
+ allDropped: true,
+ }
}
const value = await encodeLogRecords(logRecordType, compressionCodec, kept)
- return { value, pii, recordsDropped, recordsDroppedByRuleId, allDropped: false }
+ return {
+ value,
+ pii,
+ recordsDropped,
+ recordsDroppedByRuleId,
+ bytesDropped,
+ bytesDroppedByRuleId,
+ allDropped: false,
+ }
}
/**