: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
fix(ingestion): record autoscaling and transport metrics on the gRPC ingest path (#89907)
José Sequeira19bb5f6a6c31
diff --git a/nodejs/src/ingestion/api/batch-metrics.ts b/nodejs/src/ingestion/api/batch-metrics.tsnew file mode 100644index 000000000000..a3b163888bab--- /dev/null+++ b/nodejs/src/ingestion/api/batch-metrics.ts@@ -0,0 +1,96 @@+import { Counter, Gauge, Histogram } from 'prom-client'++/**+ * Batch accounting shared by the HTTP and gRPC ingest transports. The+ * processor autoscaler reads these series, so a transport that skips them+ * makes its pods look idle to KEDA however much work they hold.+ */++const batchesProcessed = new Counter({+ name: 'ingestion_api_batches_processed_total',+ help: 'Total number of batches processed by the ingestion API',+})++const batchProcessingDuration = new Histogram({+ name: 'ingestion_api_batch_processing_duration_ms',+ help: 'Duration of batch processing in milliseconds',+ buckets: [10, 50, 100, 250, 500, 1000, 2500, 5000, 10000],+})++const messagesProcessed = new Counter({+ name: 'ingestion_api_messages_processed_total',+ help: 'Total number of messages processed by the ingestion API',+})++const batchErrors = new Counter({+ name: 'ingestion_api_batch_errors_total',+ help: 'Total number of batch processing errors',+})++const batchCapacityRejections = new Counter({+ name: 'ingestion_api_batch_capacity_rejections_total',+ help: 'Total number of batches rejected because the pipeline was at concurrent batch capacity',+})++const batchesInFlight = new Gauge({+ name: 'ingestion_api_batches_in_flight',+ help: 'Number of accepted batches currently being processed by the ingestion API (concurrent batches)',+})++// Companion to `batchesInFlight`, and the one to autoscale on: batch sizes vary+// several-fold with consumer batching and routing, so a batch count says little+// about how much work a pod is holding. Events in flight is invariant to how the+// consumer slices a batch, which keeps a scaling target stable across dispatcher+// tuning changes.+const eventsInFlight = new Gauge({+ name: 'ingestion_api_events_in_flight',+ help: 'Number of events in accepted batches currently being processed by the ingestion API',+})++// The integral of `eventsInFlight` over time, accumulated one batch at a time:+// a batch holding N events for T seconds contributes N*T. Because+// integral(in_flight dt) equals sum(events * time in flight), rate() over this+// counter is the exact time-weighted mean events in flight for the interval,+// where the gauge above only reports whatever instant the scrape happened to+// land on. In-flight turns over on a sub-second timescale and scrapes are tens+// of seconds apart, so the gauge is far too noisy to autoscale on directly.+// Same relationship as container_cpu_usage_seconds_total and CPU utilization.+const eventSecondsInFlight = new Counter({+ name: 'ingestion_api_event_seconds_in_flight_total',+ help: 'Cumulative event-seconds spent in flight; rate() gives mean events in flight',+})++/** A batch the pipeline accepted, held until `batchReleased` credits its time in flight. */+export interface AcceptedBatch {+ events: number+ acceptedAt: number+}++/** The pipeline accepted the batch: it occupies a concurrent slot from now on. */+export function batchAccepted(events: number): AcceptedBatch {+ batchesInFlight.inc()+ eventsInFlight.inc(events)+ return { events, acceptedAt: Date.now() }+}++/** The batch's side effects are durably done and it was acked to the consumer. */+export function batchProcessed(batch: AcceptedBatch): void {+ batchesProcessed.inc()+ messagesProcessed.inc(batch.events)+ batchProcessingDuration.observe(Date.now() - batch.acceptedAt)+}++export function batchFailed(): void {+ batchErrors.inc()+}++export function batchRejectedAtCapacity(): void {+ batchCapacityRejections.inc()+}++/** The batch left the pipeline, acked or failed: free its slot and credit its event-seconds. */+export function batchReleased(batch: AcceptedBatch): void {+ batchesInFlight.dec()+ eventsInFlight.dec(batch.events)+ eventSecondsInFlight.inc((batch.events * (Date.now() - batch.acceptedAt)) / 1000)+}diff --git a/nodejs/src/ingestion/api/grpc-server.test.ts b/nodejs/src/ingestion/api/grpc-server.test.tsindex 28749a111256..dfed97e997f9 100644--- a/nodejs/src/ingestion/api/grpc-server.test.ts+++ b/nodejs/src/ingestion/api/grpc-server.test.ts@@ -197,6 +197,12 @@ async function slotWaiters(): Promise<number> {return value ?? 0}+async function metricValue(name: string): Promise<number> {+ const metric = register.getSingleMetric(name)+ const value = (await metric!.get()).values[0]?.value+ return value ?? 0+}+describe('WorkerIngestServer', () => {let server: WorkerIngestServerlet driver: FakeDriver@@ -461,6 +467,45 @@ describe('WorkerIngestServer', () => {}})+ it('records an accepted sub-batch in the shared in-flight metrics until it settles', async () => {+ // Regression: the processor autoscaler reads ingestion_api_events_in_flight+ // and ingestion_api_event_seconds_in_flight_total, which only the HTTP+ // handler recorded — so pods serving the gRPC transport looked idle to+ // KEDA and the worker HPA metric read 0.+ // The metrics are process-global, so assert deltas against a baseline.+ const baseline = {+ batches: await metricValue('ingestion_api_batches_in_flight'),+ events: await metricValue('ingestion_api_events_in_flight'),+ eventSeconds: await metricValue('ingestion_api_event_seconds_in_flight_total'),+ processed: await metricValue('ingestion_api_batches_processed_total'),+ messages: await metricValue('ingestion_api_messages_processed_total'),+ }+ const source = new FrameSource()+ const collected = collect(server, source)++ source.push(hello())+ source.push(subBatch(1, [10, 11, 12]))+ await until(() => driver.feeds.length === 1)+ const streamId = driver.feeds[0].streamId+ expect(await metricValue('ingestion_api_batches_in_flight')).toBe(baseline.batches + 1)+ expect(await metricValue('ingestion_api_events_in_flight')).toBe(baseline.events + 3)++ // Completion alone is not settlement: the batch stays in flight until+ // its side effects are done, matching the HTTP path's response barrier.+ const settled = new Deferred<void>()+ driver.complete({ streamId, seq: 1, accepted: 3 }, settled.promise)+ await new Promise((resolve) => setTimeout(resolve, 20))+ expect(await metricValue('ingestion_api_events_in_flight')).toBe(baseline.events + 3)++ settled.resolve()+ await until(() => collected.acks.length === 1)+ expect(await metricValue('ingestion_api_batches_in_flight')).toBe(baseline.batches)+ expect(await metricValue('ingestion_api_events_in_flight')).toBe(baseline.events)+ expect(await metricValue('ingestion_api_event_seconds_in_flight_total')).toBeGreaterThan(baseline.eventSeconds)+ expect(await metricValue('ingestion_api_batches_processed_total')).toBe(baseline.processed + 1)+ expect(await metricValue('ingestion_api_messages_processed_total')).toBe(baseline.messages + 3)+ })+it('a slow batch settlement does not block another sub-batch ack', async () => {// Regression: the pump awaited each completed batch's side effects// before pulling the next completion, head-of-line blocking everydiff --git a/nodejs/src/ingestion/api/grpc-server.ts b/nodejs/src/ingestion/api/grpc-server.tsindex f6ef5571d265..f61ca1110129 100644--- a/nodejs/src/ingestion/api/grpc-server.ts+++ b/nodejs/src/ingestion/api/grpc-server.ts@@ -18,6 +18,7 @@ import {import { logger } from '~/common/utils/logger'import { FeedResult } from '~/ingestion/framework/batching-pipeline'+import { AcceptedBatch, batchAccepted, batchFailed, batchProcessed, batchReleased } from './batch-metrics'import { FeedOrderSentinel } from './feed-order-sentinel'import { SerializedKafkaMessage } from './types'@@ -346,6 +347,12 @@ export class WorkerIngestServer {private readonly drainTimeoutMs: numberprivate sessionCount = 0private readonly slots: FifoSlots+ /**+ * Fed sub-batches by `streamId:seq`, for the shared in-flight accounting the+ * processor autoscaler reads. Kept off StreamState so a batch whose stream+ * died mid-processing is still released when it settles.+ */+ private readonly acceptedBatches = new Map<string, AcceptedBatch>()constructor(private options: WorkerIngestServerOptions,@@ -540,17 +547,38 @@ export class WorkerIngestServer {try {await completed.settled} catch (error) {+ this.releaseAccepted(completed, 'failed')this.slots.release()this.fatal(error instanceof Error ? error : new Error(String(error)))return}// The batch's admission slot frees only once its side effects are// durably done, matching the HTTP path's response barrier.+ this.releaseAccepted(completed, 'ok')this.slots.release()this.ackCompleted(completed)})()}+ private acceptedKey(streamId: number, seq: number): string {+ return `${streamId}:${seq}`+ }++ private releaseAccepted(completed: CompletedSubBatch, outcome: 'ok' | 'failed'): void {+ const key = this.acceptedKey(completed.streamId, completed.seq)+ const accepted = this.acceptedBatches.get(key)+ if (!accepted) {+ return+ }+ this.acceptedBatches.delete(key)+ if (outcome === 'ok') {+ batchProcessed(accepted)+ } else {+ batchFailed()+ }+ batchReleased(accepted)+ }+private ackCompleted(completed: CompletedSubBatch): void {const stream = this.streams.get(completed.streamId)if (!stream) {@@ -732,6 +760,7 @@ export class WorkerIngestServer {const result = await this.feedGuarded(stream, seq, serialized)if (result.ok) {feedAccepted = true+ this.acceptedBatches.set(this.acceptedKey(stream.id, seq), batchAccepted(serialized.length))break}if (result.kind === 'at_capacity') {diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 00d4123835c3..b6169e954fda 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -1,5 +1,4 @@import { Message } from 'node-rdkafka'-import { Counter, Gauge, Histogram } from 'prom-client'import { IntegrationManagerService } from '~/cdp/services/managers/integration-manager.service'import { initializePrometheusLabels } from '~/common/api/router'@@ -70,6 +69,14 @@ import {} from '../cdp/hog-transformations/hog-transformer.service'import { EncryptedFields } from '../cdp/utils/encryption-utils'import { CommonConfig } from '../common/config'+import {+ AcceptedBatch,+ batchAccepted,+ batchFailed,+ batchProcessed,+ batchRejectedAtCapacity,+ batchReleased,+} from '../ingestion/api/batch-metrics'import { FeedOrderSentinel } from '../ingestion/api/feed-order-sentinel'import { WorkerIngestServer } from '../ingestion/api/grpc-server'import { deserializeKafkaMessage } from '../ingestion/api/kafka-message-converter'@@ -130,60 +137,6 @@ export type IngestionApiServerConfig = BaseServerConfig &| 'KAFKA_HEALTHCHECK_SECONDS'>-const batchesProcessed = new Counter({- name: 'ingestion_api_batches_processed_total',- help: 'Total number of batches processed by the ingestion API',-})--const batchProcessingDuration = new Histogram({- name: 'ingestion_api_batch_processing_duration_ms',- help: 'Duration of batch processing in milliseconds',- buckets: [10, 50, 100, 250, 500, 1000, 2500, 5000, 10000],-})--const messagesProcessed = new Counter({- name: 'ingestion_api_messages_processed_total',- help: 'Total number of messages processed by the ingestion API',-})--const batchErrors = new Counter({- name: 'ingestion_api_batch_errors_total',- help: 'Total number of batch processing errors',-})--const batchCapacityRejections = new Counter({- name: 'ingestion_api_batch_capacity_rejections_total',- help: 'Total number of batches rejected because the pipeline was at concurrent batch capacity',-})--const batchesInFlight = new Gauge({- name: 'ingestion_api_batches_in_flight',- help: 'Number of accepted batches currently being processed by the ingestion API (concurrent batches)',-})--// Companion to `batchesInFlight`, and the one to autoscale on: batch sizes vary-// several-fold with consumer batching and routing, so a batch count says little-// about how much work a pod is holding. Events in flight is invariant to how the-// consumer slices a batch, which keeps a scaling target stable across dispatcher-// tuning changes.-const eventsInFlight = new Gauge({- name: 'ingestion_api_events_in_flight',- help: 'Number of events in accepted batches currently being processed by the ingestion API',-})--// The integral of `eventsInFlight` over time, accumulated one batch at a time:-// a batch holding N events for T seconds contributes N*T. Because-// integral(in_flight dt) equals sum(events * time in flight), rate() over this-// counter is the exact time-weighted mean events in flight for the interval,-// where the gauge above only reports whatever instant the scrape happened to-// land on. In-flight turns over on a sub-second timescale and scrapes are tens-// of seconds apart, so the gauge is far too noisy to autoscale on directly.-// Same relationship as container_cpu_usage_seconds_total and CPU utilization.-const eventSecondsInFlight = new Counter({- name: 'ingestion_api_event_seconds_in_flight_total',- help: 'Cumulative event-seconds spent in flight; rate() gives mean events in flight',-})-/*** Ingestion API server that exposes the ingestion pipeline as an HTTP endpoint.*@@ -579,12 +532,9 @@ export class IngestionApiServer implements NodeServer {return}- const startTime = Date.now()-- // Event count and acceptance time of this batch once accepted, or null- // while it is not. Holding both (rather than a bool) makes the `finally`- // credit exactly what was counted, even if `messages` is out of scope.- let inFlight: { events: number; acceptedAt: number } | null = null+ // Set once the pipeline accepts the batch, so the `finally` releases+ // exactly what was counted.+ let inFlight: AcceptedBatch | null = nulltry {const messages: Message[] = serializedMessages.map(deserializeKafkaMessage)@@ -613,7 +563,7 @@ export class IngestionApiServer implements NodeServer {// can't silently downgrade us to a fall-through 500 — which// the Rust transport treats as retriable.if (feedResult.kind === 'at_capacity') {- batchCapacityRejections.inc()+ batchRejectedAtCapacity()res.status(503).json({batch_id: batch_id ?? '',status: 'error',@@ -627,9 +577,7 @@ export class IngestionApiServer implements NodeServer {// Batch accepted into the pipeline — it now occupies a concurrent// slot until processing completes below.- batchesInFlight.inc()- eventsInFlight.inc(messages.length)- inFlight = { events: messages.length, acceptedAt: Date.now() }+ inFlight = batchAccepted(messages.length)// The pipeline handles its own side effects (scheduling them on// the promise scheduler), so draining results is all that's left@@ -645,13 +593,11 @@ export class IngestionApiServer implements NodeServer {// afterBatch flush step, so it's covered by waitForAll().await this.promiseScheduler.waitForAll()- batchesProcessed.inc()- messagesProcessed.inc(messages.length)- batchProcessingDuration.observe(Date.now() - startTime)+ batchProcessed(inFlight)res.status(200).json({ batch_id, status: 'ok', accepted: messages.length })} catch (err) {- batchErrors.inc()+ batchFailed()const error = err instanceof Error ? err : new Error(String(err))logger.error('💥', 'Ingestion API batch processing failed', { batch_id, error: error.message })// A throw here can leave the shared pipeline permanently poisoned, so@@ -668,9 +614,7 @@ export class IngestionApiServer implements NodeServer {res.status(500).json({ batch_id, status: 'error', accepted: 0, error: error.message })} finally {if (inFlight !== null) {- batchesInFlight.dec()- eventsInFlight.dec(inFlight.events)- eventSecondsInFlight.inc((inFlight.events * (Date.now() - inFlight.acceptedAt)) / 1000)+ batchReleased(inFlight)}}}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 10768e48226e..b0650423190e 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -6015,6 +6015,7 @@ dependencies = ["lifecycle","metrics","metrics-exporter-prometheus",+ "prost 0.13.5","rand 0.8.5","rdkafka","reqwest 0.12.28",diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.tomlindex 8efece40e62a..9792e7246f70 100644--- a/rust/ingestion-consumer/Cargo.toml+++ b/rust/ingestion-consumer/Cargo.toml@@ -19,6 +19,7 @@ kube = { version = "0.98", features = ["client", "runtime"] }lifecycle = { path = "../common/lifecycle" }metrics = { workspace = true }metrics-exporter-prometheus = { workspace = true }+prost = { workspace = true }rand = { workspace = true }rdkafka = { workspace = true }reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rsindex ae21cc405b36..02d148714fbb 100644--- a/rust/ingestion-consumer/src/grpc_transport.rs+++ b/rust/ingestion-consumer/src/grpc_transport.rs@@ -45,7 +45,8 @@ use ingestion_worker_proto::ingestion::worker::v1::{ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,KafkaMessage, StreamHello, SubBatch, SubBatchStatus,};-use metrics::{counter, gauge};+use metrics::{counter, gauge, histogram};+use prost::Message;use tokio::sync::{mpsc, oneshot};use tokio_stream::wrappers::UnboundedReceiverStream;use tracing::{error, info, warn};@@ -305,6 +306,8 @@ struct LedgerEntry {/// watchdog fences on the oldest entry's deadline, so a stuck sub-batch/// times out even while its siblings keep acking.deadline: tokio::time::Instant,+ /// When the sub-batch went on the wire, for the send-to-ack latency histogram.+ sent_at: std::time::Instant,/// The worker's accepted count once acked. The entry stays in the ledger/// until every earlier entry is acked too, so a fence still reaches it.acked: Option<u32>,@@ -392,8 +395,7 @@ impl WorkerStreamRunner {};let mut next_seq = 1u64;- gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())- .set(0.0);+ self.record_ledger_depth(0);loop {if let Err(end) = self.fill_ledger(@@ -534,23 +536,39 @@ impl WorkerStreamRunner {assignment_epoch: self.assignment_epoch.load(Ordering::Relaxed),})),};+ // tonic gzips the frame after this point, so only the raw size is observable here.+ counter!("ingestion_consumer_transport_body_bytes_total", "encoding" => "protobuf")+ .increment(request.encoded_len() as u64);let deadline = tokio::time::Instant::now() + self.ack_timeout;let sent = out_tx.send(request).is_ok();ledger.push_back(LedgerEntry {seq,item,deadline,+ sent_at: std::time::Instant::now(),acked: None,});if !sent {return Err(self.fence(None, ledger, queue, "stream closed mid-send"));}- gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())- .set(ledger.len() as f64);+ self.record_ledger_depth(ledger.len());}Ok(())}+ /// Un-acked sub-batches on the stream, also published as the per-worker in-flight gauge.+ fn record_ledger_depth(&self, depth: usize) {+ gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())+ .set(depth as f64);+ gauge!("ingestion_consumer_transport_concurrent_batches", "worker" => self.worker_url.clone())+ .set(depth as f64);+ }++ fn record_send_duration(&self, entry: &LedgerEntry) {+ histogram!("ingestion_consumer_transport_duration_seconds", "worker" => self.worker_url.clone())+ .record(entry.sent_at.elapsed().as_secs_f64());+ }+/// Wait for an ack, or for new work when the ledger has room. `Ok(None)`/// means new work was held in `pending_first`; `Err` ends the stream.///@@ -651,6 +669,7 @@ impl WorkerStreamRunner {);return Err(self.fence_with(true, None, ledger, queue, "worker busy"));}+ let was_full = ledger.len() >= self.max_unacked;let Some(entry) = ledger.iter_mut().find(|e| e.seq == response.seq && e.acked.is_none())@@ -659,6 +678,7 @@ impl WorkerStreamRunner {return Err(self.fence(None, ledger, queue, "unknown ack seq"));};entry.acked = Some(response.accepted);+ self.record_send_duration(entry);counter!("ingestion_consumer_transport_requests_total","worker" => self.worker_url.clone(),@@ -676,8 +696,14 @@ impl WorkerStreamRunner {} = entry.item;let _ = reply.send(Ok(Accepted { accepted, messages }));}- gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())- .set(ledger.len() as f64);+ if was_full && ledger.len() < self.max_unacked && !queue.is_empty() {+ counter!(+ "ingestion_consumer_transport_backpressure_waits_total",+ "worker" => self.worker_url.clone()+ )+ .increment(1);+ }+ self.record_ledger_depth(ledger.len());Ok(())}@@ -711,6 +737,9 @@ impl WorkerStreamRunner {) -> StreamEnd {let mut fence = Fence::new(retriable, reason);for entry in ledger.drain(..) {+ if entry.acked.is_none() {+ self.record_send_duration(&entry);+ }fence.fail(entry.item);}if let Some(item) = pending_first {@@ -725,8 +754,7 @@ impl WorkerStreamRunner {"status" => if retriable { "busy" } else { "error" }).increment(1);- gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())- .set(0.0);+ self.record_ledger_depth(0);StreamEnd::Failed(fence)}}