: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(ingestion): export librdkafka broker request stats for producers (#106494)
Robbieaf44c1c7e0ce
diff --git a/nodejs/src/common/kafka/kafka-producer-metrics.test.ts b/nodejs/src/common/kafka/kafka-producer-metrics.test.tsindex bdaf75c926fd..dfc349557398 100644--- a/nodejs/src/common/kafka/kafka-producer-metrics.test.ts+++ b/nodejs/src/common/kafka/kafka-producer-metrics.test.ts@@ -2,12 +2,16 @@ import { Gauge, register } from 'prom-client'import {ProducerStatsTracker,+ kafkaProducerBrokerLatencySeconds,kafkaProducerBrokers,+ kafkaProducerBusiestBrokerRequestsInFlight,kafkaProducerCallbackQueueDepth,kafkaProducerQueueBytes,kafkaProducerQueueMaxBytes,kafkaProducerQueueMaxMessages,kafkaProducerQueueMessages,+ kafkaProducerRequestsInFlight,+ kafkaProducerRequestsQueued,kafkaProducerTopicBatchCountAvg,kafkaProducerTopicBatchSizeBytesAvg,} from './kafka-producer-metrics'@@ -93,6 +97,50 @@ describe('ProducerStatsTracker', () => {expect(await gaugeValue(kafkaProducerBrokers, { producer_name: 'DEFAULT', state: 'UP' })).toBe(1)})+ it('rolls up broker requests and latency windows across learned brokers', async () => {+ const tracker = new ProducerStatsTracker('DEFAULT')++ tracker.track(+ makeStats({+ brokers: {+ 'kafka-1:9092/bootstrap': {+ nodeid: -1,+ state: 'UP',+ waitresp_cnt: 100,+ outbuf_cnt: 100,+ rtt: { sum: 90_000_000, cnt: 1, p99: 90_000_000 },+ },+ 'kafka-1:9092/1': {+ nodeid: 1,+ state: 'UP',+ waitresp_cnt: 5,+ outbuf_cnt: 7,+ rtt: { sum: 1_200_000, cnt: 3, p99: 600_000 },+ outbuf_latency: { sum: 0, cnt: 0, p99: 0 },+ },+ 'kafka-2:9092/2': {+ nodeid: 2,+ state: 'UP',+ waitresp_cnt: 2,+ outbuf_cnt: 0,+ rtt: { sum: 200_000, cnt: 1, p99: 200_000 },+ },+ },+ })+ )++ const labels = { producer_name: 'DEFAULT' }+ expect(await gaugeValue(kafkaProducerRequestsInFlight, labels)).toBe(7)+ expect(await gaugeValue(kafkaProducerBusiestBrokerRequestsInFlight, labels)).toBe(5)+ expect(await gaugeValue(kafkaProducerRequestsQueued, labels)).toBe(7)+ const latency = (name: string, stat: string): Promise<number | undefined> =>+ gaugeValue(kafkaProducerBrokerLatencySeconds, { ...labels, latency: name, stat })+ expect(await latency('round_trip', 'mean')).toBeCloseTo(0.35)+ expect(await latency('round_trip', 'max_p99')).toBeCloseTo(0.6)+ expect(await latency('request_queue', 'mean')).toBe(0)+ expect(await latency('request_queue', 'max_p99')).toBe(0)+ })+it('sets per-topic batching gauges', async () => {const tracker = new ProducerStatsTracker('DEFAULT')diff --git a/nodejs/src/common/kafka/kafka-producer-metrics.ts b/nodejs/src/common/kafka/kafka-producer-metrics.tsindex de4a4ed8d28a..548c74cb01dd 100644--- a/nodejs/src/common/kafka/kafka-producer-metrics.ts+++ b/nodejs/src/common/kafka/kafka-producer-metrics.ts@@ -2,7 +2,7 @@ import { Gauge } from 'prom-client'import { parseJSON } from '../utils/json-parse'import { logger } from '../utils/logger'-import { producerStatsSchema } from './kafka-producer-stats-schema'+import { BrokerStats, LatencyWindowMicroseconds, producerStatsSchema } from './kafka-producer-stats-schema'export const kafkaProducerQueueMessages = new Gauge({name: 'kafka_producer_queue_messages',@@ -40,6 +40,30 @@ export const kafkaProducerBrokers = new Gauge({labelNames: ['producer_name', 'state'],})+export const kafkaProducerRequestsInFlight = new Gauge({+ name: 'kafka_producer_requests_in_flight',+ help: 'Requests sent to brokers that still wait for a response, summed over brokers.',+ labelNames: ['producer_name'],+})++export const kafkaProducerRequestsQueued = new Gauge({+ name: 'kafka_producer_requests_queued',+ help: 'Requests in broker output buffers that librdkafka has not sent yet, summed over brokers.',+ labelNames: ['producer_name'],+})++export const kafkaProducerBusiestBrokerRequestsInFlight = new Gauge({+ name: 'kafka_producer_busiest_broker_requests_in_flight',+ help: 'Requests in flight on the broker connection that has the most. Compare with max.in.flight.requests.per.connection.',+ labelNames: ['producer_name'],+})++export const kafkaProducerBrokerLatencySeconds = new Gauge({+ name: 'kafka_producer_broker_latency_seconds',+ help: 'librdkafka broker latency over the last stats window. stat=mean is over all brokers; stat=max_p99 is the highest broker p99. latency=internal_queue is the partition queue wait, request_queue is the output buffer wait, round_trip is the broker RTT.',+ labelNames: ['producer_name', 'latency', 'stat'],+})+export const kafkaProducerTopicBatchSizeBytesAvg = new Gauge({name: 'kafka_producer_topic_batch_size_bytes_avg',help: 'Average Kafka produce batch size in bytes, per topic, over the rolling librdkafka window.',@@ -110,14 +134,19 @@ export class ProducerStatsTracker {if (stats.brokers) {const countsByState = new Map<string, number>()+ const learnedBrokers: BrokerStats[] = []for (const broker of Object.values(stats.brokers)) {// librdkafka lists configured bootstrap servers with nodeid -1 next to the learned brokers.const isBootstrap = broker.nodeid !== undefined && broker.nodeid < 0- if (broker.state === undefined || isBootstrap) {+ if (isBootstrap) {continue}- countsByState.set(broker.state, (countsByState.get(broker.state) ?? 0) + 1)+ learnedBrokers.push(broker)+ if (broker.state !== undefined) {+ countsByState.set(broker.state, (countsByState.get(broker.state) ?? 0) + 1)+ }}+ this.trackBrokerRequests(learnedBrokers)for (const state of this.reportedBrokerStates) {if (!countsByState.has(state)) {kafkaProducerBrokers.set({ ...labels, state }, 0)@@ -141,4 +170,53 @@ export class ProducerStatsTracker {}}}++ private trackBrokerRequests(brokers: BrokerStats[]): void {+ const labels = { producer_name: this.producerName }+ const inFlightPerBroker = brokers.map((broker) => broker.waitresp_cnt ?? 0)+ kafkaProducerRequestsInFlight.set(+ labels,+ inFlightPerBroker.reduce((sum, count) => sum + count, 0)+ )+ kafkaProducerBusiestBrokerRequestsInFlight.set(labels, Math.max(0, ...inFlightPerBroker))+ kafkaProducerRequestsQueued.set(+ labels,+ brokers.reduce((sum, broker) => sum + (broker.outbuf_cnt ?? 0), 0)+ )+ this.trackBrokerLatency(+ 'internal_queue',+ brokers.map((broker) => broker.int_latency)+ )+ this.trackBrokerLatency(+ 'request_queue',+ brokers.map((broker) => broker.outbuf_latency)+ )+ this.trackBrokerLatency(+ 'round_trip',+ brokers.map((broker) => broker.rtt)+ )+ }++ private trackBrokerLatency(+ latency: 'internal_queue' | 'request_queue' | 'round_trip',+ windows: (LatencyWindowMicroseconds | undefined)[]+ ): void {+ let sumMicroseconds = 0+ let sampleCount = 0+ let maxP99Microseconds = 0+ for (const window of windows) {+ if (!window?.cnt) {+ continue+ }+ sumMicroseconds += window.sum ?? 0+ sampleCount += window.cnt+ maxP99Microseconds = Math.max(maxP99Microseconds, window.p99 ?? 0)+ }+ const labels = { producer_name: this.producerName, latency }+ kafkaProducerBrokerLatencySeconds.set(+ { ...labels, stat: 'mean' },+ sampleCount > 0 ? sumMicroseconds / sampleCount / 1e6 : 0+ )+ kafkaProducerBrokerLatencySeconds.set({ ...labels, stat: 'max_p99' }, maxP99Microseconds / 1e6)+ }}diff --git a/nodejs/src/common/kafka/kafka-producer-stats-schema.ts b/nodejs/src/common/kafka/kafka-producer-stats-schema.tsindex fd1e430f00ad..564c3a130858 100644--- a/nodejs/src/common/kafka/kafka-producer-stats-schema.ts+++ b/nodejs/src/common/kafka/kafka-producer-stats-schema.ts@@ -12,9 +12,20 @@ import { z } from 'zod'* break the parse.*/+const latencyWindowMicrosecondsSchema = z.object({+ sum: z.number().optional(),+ cnt: z.number().optional(),+ p99: z.number().optional(),+})+const brokerStatsSchema = z.object({nodeid: z.number().optional(),state: z.string().optional(),+ outbuf_cnt: z.number().optional(),+ waitresp_cnt: z.number().optional(),+ int_latency: latencyWindowMicrosecondsSchema.optional(),+ outbuf_latency: latencyWindowMicrosecondsSchema.optional(),+ rtt: latencyWindowMicrosecondsSchema.optional(),})const topicStatsSchema = z.object({@@ -34,4 +45,5 @@ export const producerStatsSchema = z.object({export type ProducerStats = z.infer<typeof producerStatsSchema>export type BrokerStats = z.infer<typeof brokerStatsSchema>+export type LatencyWindowMicroseconds = z.infer<typeof latencyWindowMicrosecondsSchema>export type TopicStats = z.infer<typeof topicStatsSchema>