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(capture): cap ingestion warnings per type per pod (#108098)

Eli Reismanb7a11689d4b0
diff --git a/.agents/skills/adding-ingestion-warnings/SKILL.md b/.agents/skills/adding-ingestion-warnings/SKILL.md
index 0c25129b13ee..ed0af4e0884d 100644
--- a/.agents/skills/adding-ingestion-warnings/SKILL.md
+++ b/.agents/skills/adding-ingestion-warnings/SKILL.md
@@ -97,7 +97,7 @@ Emitting from Rust:
- **Emit it** via `WarningEmitter::emit(token, source, warning, details, count)` — the builder injects `count` and `pipelineStep` into details and stamps `type`/`source`/`details` into the event properties the consumer reads. Use the same camelCase details keys as nodejs (`distinctId`, `eventUuid`, ...). The envelope's top-level `distinct_id` is always the token (never the offending id), so an oversized offending distinct_id can't make the consumer drop the warning.
- **`source` identifies the producer** (`src/lib.rs`): a `WarningSource { service, path, pipeline_step }`. `service` is the stable message `source` field and metric label (e.g. `"capture"`) — pick one per service, don't invent a new value per call site. `path` is metric-only, for splitting volume within one service's emit sites (e.g. `"v1_analytics"`); it never reaches the message. `pipeline_step` is stamped into the envelope's details as `pipelineStep`. Capture declares one source per emit site: `CAPTURE_V1_ANALYTICS` and `CAPTURE_V1_RATE_LIMIT` (path `v1_analytics`), `CAPTURE_LEGACY_ANALYTICS` and `CAPTURE_LEGACY_RATE_LIMIT` (path `legacy_analytics`), `CAPTURE_AI_EVENTS` (path `ai_events`), `CAPTURE_AI_OTEL` (path `ai_otel`), and `CAPTURE_REPLAY` (path `replay`) — see the constants in `src/lib.rs` for the current list.
-- **Best-effort, fire-and-forget**: throttled per `(token, type)` per pod, never awaited, never fails the caller. Capture gates it behind `CAPTURE_INGESTION_WARNINGS_ENABLED` (default off; see `rust/capture/src/config.rs`). The producer is a `common-kafka` `ThreadedProducer` (built via `create_threaded_kafka_producer_no_ping` with `observe_delivery` as its delivery callback, so delivered/failed outcomes are counted on the producer's own poll thread — no per-message task). It runs on its own dedicated `KafkaConfig` and its own destination: the emitter reads only `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TOPIC,TLS}` and never falls back to the main event cluster's `KAFKA_*` settings, so a deployment whose sink and warnings destination are different clusters (capture-ai produces events to WarpStream but warnings to MSK) is configurable. Empty hosts or topic means the emitter reports itself disabled rather than guessing. the fire-and-forget policy (`client.id=capture-ingestion-warnings`, `acks=1`, `retries=0`, `linger.ms=100`, a bounded 10k-message queue, a 5s message timeout) is fixed in code as the `WARNINGS_KAFKA_*` constants in `rust/capture/src/setup.rs` — not env-configurable — while only the two capacity/safety limits stay tunable via env (`CAPTURE_INGESTION_WARNINGS_KAFKA_QUEUE_MIB` and `..._MESSAGE_MAX_BYTES`). So a slow or saturated warnings topic can never contend with the main event producer.
+- **Best-effort, fire-and-forget**: throttled per `(token, type)` per pod, never awaited, never fails the caller. Capture also caps each warning type per pod (the `WARNINGS_TYPE_BUDGET_*` constants in `rust/capture/src/setup.rs`), so a failure that hits many tokens at once cannot flood the topic; drops are counted as `outcome="type_budget_exhausted"`. Capture gates it behind `CAPTURE_INGESTION_WARNINGS_ENABLED` (default off; see `rust/capture/src/config.rs`). The producer is a `common-kafka` `ThreadedProducer` (built via `create_threaded_kafka_producer_no_ping` with `observe_delivery` as its delivery callback, so delivered/failed outcomes are counted on the producer's own poll thread — no per-message task). It runs on its own dedicated `KafkaConfig` and its own destination: the emitter reads only `CAPTURE_INGESTION_WARNINGS_KAFKA_{HOSTS,TOPIC,TLS}` and never falls back to the main event cluster's `KAFKA_*` settings, so a deployment whose sink and warnings destination are different clusters (capture-ai produces events to WarpStream but warnings to MSK) is configurable. Empty hosts or topic means the emitter reports itself disabled rather than guessing. the fire-and-forget policy (`client.id=capture-ingestion-warnings`, `acks=1`, `retries=0`, `linger.ms=100`, a bounded 10k-message queue, a 5s message timeout) is fixed in code as the `WARNINGS_KAFKA_*` constants in `rust/capture/src/setup.rs` — not env-configurable — while only the two capacity/safety limits stay tunable via env (`CAPTURE_INGESTION_WARNINGS_KAFKA_QUEUE_MIB` and `..._MESSAGE_MAX_BYTES`). So a slow or saturated warnings topic can never contend with the main event producer.
- **Crate deps**: `common-ingestion-warnings` depends on `common-types` (for `CapturedEvent`) and `common-kafka` (the producer) — not on `capture` or any service crate. `WarningEmitter` is a plain trait object (`Arc<dyn WarningEmitter>`), so any Rust service can depend on the crate and wire it the way capture does in `router::State` / `setup.rs`; a team-aware service just supplies its own token.
## Rolling out a new capture-produced type
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index e3373541dc6c..bd6b2e7285b0 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2978,6 +2978,7 @@ dependencies = [
"common-types",
"governor",
"metrics",
+ "metrics-util",
"rdkafka",
"rstest",
"serde_json",
diff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rs
index 83eac5dbfed7..597df18d41f4 100644
--- a/rust/capture/src/setup.rs
+++ b/rust/capture/src/setup.rs
@@ -1,11 +1,13 @@
use std::collections::HashMap;
+use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use anyhow::Context;
use axum::Router;
use common_ingestion_warnings::{
- observe_delivery, KafkaWarningEmitter, WarningEmitter, INGESTION_WARNINGS_EMITTER_ENABLED,
+ observe_delivery, KafkaWarningEmitter, WarningEmitter, WarningThrottle,
+ INGESTION_WARNINGS_EMITTER_ENABLED,
};
use common_kafka::config::KafkaConfig as WarningsKafkaConfig;
use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;
@@ -706,6 +708,12 @@ const WARNINGS_KAFKA_LINGER_MS: u32 = 100;
const WARNINGS_KAFKA_QUEUE_MESSAGES: u32 = 10_000;
// Drop a message not delivered within this many ms.
const WARNINGS_KAFKA_MESSAGE_TIMEOUT_MS: u32 = 5_000;
+// Per-type budget per pod: a burst of 60 that refills one a second, so about
+// 60 warnings of one type a minute. It caps what a failure that hits many
+// tokens at once can send, because the per-token throttle alone scales with
+// the number of tokens.
+const WARNINGS_TYPE_BUDGET_PERIOD: Duration = Duration::from_secs(1);
+const WARNINGS_TYPE_BUDGET_BURST: NonZeroU32 = NonZeroU32::new(60).unwrap();
/// Build the dedicated, warnings-only Kafka config. Reuses only the
/// destination cluster (`hosts`/`tls`) from capture's main Kafka config;
@@ -823,7 +831,13 @@ async fn create_ingestion_warning_emitter(
}
};
- let emitter = Arc::new(KafkaWarningEmitter::new(producer, topic.clone()));
+ let throttle = WarningThrottle::default()
+ .with_type_budget(WARNINGS_TYPE_BUDGET_PERIOD, WARNINGS_TYPE_BUDGET_BURST);
+ let emitter = Arc::new(KafkaWarningEmitter::with_throttle(
+ producer,
+ topic.clone(),
+ throttle,
+ ));
let emitter_bg = emitter.clone();
tokio::spawn(async move {
diff --git a/rust/common/ingestion_warnings/Cargo.toml b/rust/common/ingestion_warnings/Cargo.toml
index e0d338f07b54..349ef35d7d83 100644
--- a/rust/common/ingestion_warnings/Cargo.toml
+++ b/rust/common/ingestion_warnings/Cargo.toml
@@ -24,4 +24,5 @@ uuid = { workspace = true }
[dev-dependencies]
common-liveness = { path = "../liveness" }
+metrics-util = { workspace = true }
rstest = "0.26"
diff --git a/rust/common/ingestion_warnings/src/lib.rs b/rust/common/ingestion_warnings/src/lib.rs
index 9ea8f499e9c5..b10a90350098 100644
--- a/rust/common/ingestion_warnings/src/lib.rs
+++ b/rust/common/ingestion_warnings/src/lib.rs
@@ -10,7 +10,8 @@
//!
//! Envelope producers call [`WarningEmitter::emit`] with the offending
//! event's API token, a source, a registered [`WarningType`], and caller
-//! context; the emitter throttles per `(token, type)`, builds a
+//! context; the emitter throttles per `(token, type)` (and per type, when
+//! configured), builds a
//! `$$client_ingestion_warning` [`common_types::CapturedEvent`] envelope,
//! and enqueues it to a producer without ever awaiting delivery. Everything
//! fails open: a throttled, unserializable, or unenqueueable warning is
@@ -61,7 +62,8 @@ pub use throttle::{ThrottleDecision, WarningThrottle};
/// (producing service, matches the message's `source` field), `path`
/// (metric-only, finer-grained attribution within one service), and
/// `outcome`. Enqueue-time outcomes: `emitted | throttled |
-/// cardinality_capped | queue_full | serialize_error | enqueue_error`.
+/// cardinality_capped | type_budget_exhausted | queue_full | serialize_error |
+/// enqueue_error`.
/// Delivery-time outcomes (reported asynchronously for each `emitted`
/// message): `delivered | delivery_failed`.
///
@@ -242,11 +244,21 @@ impl KafkaWarningEmitter {
pub fn new(
producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,
topic: impl Into<String>,
+ ) -> Self {
+ Self::with_throttle(producer, topic, WarningThrottle::default())
+ }
+
+ /// Construct with an explicit throttle, for example one with a per-type
+ /// budget ([`WarningThrottle::with_type_budget`]).
+ pub fn with_throttle(
+ producer: ThreadedProducer<ThreadedKafkaContext<WarningDelivery>>,
+ topic: impl Into<String>,
+ throttle: WarningThrottle,
) -> Self {
Self {
producer,
topic: topic.into(),
- throttle: WarningThrottle::default(),
+ throttle,
}
}
@@ -270,30 +282,16 @@ impl WarningEmitter for KafkaWarningEmitter {
// Key by token so one team's warnings stay partition-local and
// throttle-independent from every other team's, matching the Node.js
// consumer's per-team keying downstream.
- match self.throttle.check(&token, warning) {
- ThrottleDecision::Emit => {}
- ThrottleDecision::Throttled => {
- counter!(
- INGESTION_WARNINGS_TOTAL,
- "type" => warning.as_str(),
- "source" => source.service,
- "path" => source.path,
- "outcome" => "throttled",
- )
- .increment(1);
- return;
- }
- ThrottleDecision::CardinalityCapped => {
- counter!(
- INGESTION_WARNINGS_TOTAL,
- "type" => warning.as_str(),
- "source" => source.service,
- "path" => source.path,
- "outcome" => "cardinality_capped",
- )
- .increment(1);
- return;
- }
+ if let Some(outcome) = self.throttle.check(&token, warning).drop_outcome() {
+ counter!(
+ INGESTION_WARNINGS_TOTAL,
+ "type" => warning.as_str(),
+ "source" => source.service,
+ "path" => source.path,
+ "outcome" => outcome,
+ )
+ .increment(1);
+ return;
}
let serialized = serializer::Warning::new(warning)
@@ -431,7 +429,10 @@ pub fn observe_delivery(result: &DeliveryResult, delivery: WarningDelivery) {
mod tests {
use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::create_threaded_kafka_producer_no_ping;
+ use std::num::NonZeroU32;
+
use common_liveness::SyncLivenessReporter;
+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use rstest::rstest;
use super::*;
@@ -516,4 +517,46 @@ mod tests {
"emit must be fire-and-forget"
);
}
+
+ #[test]
+ fn kafka_emitter_counts_type_budget_drops() {
+ let throttle = WarningThrottle::default()
+ .with_type_budget(throttle::DEFAULT_THROTTLE_PERIOD, NonZeroU32::MIN);
+ let emitter = KafkaWarningEmitter::with_throttle(
+ unreachable_producer(500, 5),
+ "client_ingestion_warning",
+ throttle,
+ );
+ let recorder = DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ metrics::with_local_recorder(&recorder, || {
+ for token in ["tok_a", "tok_b"] {
+ emitter.emit(
+ token.to_string(),
+ CAPTURE_V1_ANALYTICS,
+ WarningType::InvalidOptions,
+ Map::new(),
+ 1,
+ );
+ }
+ });
+
+ let exhausted: Vec<u64> = snapshotter
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .filter(|(ckey, _, _, _)| {
+ ckey.key().name() == INGESTION_WARNINGS_TOTAL
+ && ckey
+ .key()
+ .labels()
+ .any(|l| l.key() == "outcome" && l.value() == "type_budget_exhausted")
+ })
+ .map(|(_, _, _, value)| match value {
+ DebugValue::Counter(n) => n,
+ other => panic!("expected a counter, got {other:?}"),
+ })
+ .collect();
+ assert_eq!(exhausted, vec![1]);
+ }
}
diff --git a/rust/common/ingestion_warnings/src/throttle.rs b/rust/common/ingestion_warnings/src/throttle.rs
index 0b2141a555bc..988668afd00e 100644
--- a/rust/common/ingestion_warnings/src/throttle.rs
+++ b/rust/common/ingestion_warnings/src/throttle.rs
@@ -5,6 +5,10 @@
//! Combined with per-batch dedup at the emit site, steady-state volume is
//! bounded at roughly `affected tokens × warning types` messages per hour per
//! pod regardless of traffic.
+//!
+//! An optional per-type budget ([`WarningThrottle::with_type_budget`]) also
+//! caps how many warnings of one type a pod sends, whatever the number of
+//! tokens.
use std::num::NonZeroU32;
use std::time::Duration;
@@ -23,6 +27,11 @@ pub const DEFAULT_THROTTLE_PERIOD: Duration = Duration::from_secs(3600);
pub const DEFAULT_MAX_TRACKED_KEYS: usize = 100_000;
type Key = (String, crate::registry::WarningType);
+type TypeBudget = RateLimiter<
+ crate::registry::WarningType,
+ DefaultKeyedStateStore<crate::registry::WarningType>,
+ clock::DefaultClock,
+>;
/// Outcome of a throttle check; names align with the emission metric's
/// `outcome` label values.
@@ -35,12 +44,28 @@ pub enum ThrottleDecision {
/// The key map is at capacity (token-flood guard) — drop without
/// consulting or growing the limiter.
CardinalityCapped,
+ /// This warning type used up its per-pod budget, so drop.
+ TypeBudgetExhausted,
+}
+
+impl ThrottleDecision {
+ /// The metric `outcome` label for a dropped warning, or `None` for
+ /// [`ThrottleDecision::Emit`].
+ pub fn drop_outcome(self) -> Option<&'static str> {
+ match self {
+ Self::Emit => None,
+ Self::Throttled => Some("throttled"),
+ Self::CardinalityCapped => Some("cardinality_capped"),
+ Self::TypeBudgetExhausted => Some("type_budget_exhausted"),
+ }
+ }
}
/// Keyed governor rate limiter over `(token, WarningType)`.
pub struct WarningThrottle {
limiter: RateLimiter<Key, DefaultKeyedStateStore<Key>, clock::DefaultClock>,
max_tracked_keys: usize,
+ type_budget: Option<TypeBudget>,
}
impl WarningThrottle {
@@ -54,6 +79,7 @@ impl WarningThrottle {
Self {
limiter: RateLimiter::dashmap(quota),
max_tracked_keys: DEFAULT_MAX_TRACKED_KEYS,
+ type_budget: None,
}
}
@@ -63,18 +89,42 @@ impl WarningThrottle {
self
}
+ /// Cap the warnings of each type that pass the per-`(token, type)` check
+ /// at `burst`, refilling one permit per `period`. This bounds what one
+ /// failure that hits many tokens at once can send. Off by default.
+ pub fn with_type_budget(mut self, period: Duration, burst: NonZeroU32) -> Self {
+ let quota = Quota::with_period(period)
+ .expect("type budget period must be non-zero")
+ .allow_burst(burst);
+ self.type_budget = Some(RateLimiter::dashmap(quota));
+ self
+ }
+
/// Consume a permit for this `(token, type)` if the key map has room and
- /// the key has budget. Anything but [`ThrottleDecision::Emit`] means the
- /// caller should drop the warning.
+ /// the key has budget, then a permit of the type budget if one is set.
+ /// Anything but [`ThrottleDecision::Emit`] means the caller should drop the
+ /// warning.
pub fn check(&self, token: &str, warning: crate::registry::WarningType) -> ThrottleDecision {
// Governor's keyed limiter inserts on lookup, so the cap must gate
// every check — including keys already tracked — to stay O(1).
if self.limiter.len() >= self.max_tracked_keys {
return ThrottleDecision::CardinalityCapped;
}
- match self.limiter.check_key(&(token.to_string(), warning)) {
- Ok(()) => ThrottleDecision::Emit,
- Err(_) => ThrottleDecision::Throttled,
+ if self
+ .limiter
+ .check_key(&(token.to_string(), warning))
+ .is_err()
+ {
+ return ThrottleDecision::Throttled;
+ }
+ // The type budget comes second, so a token that repeats a warning
+ // spends at most one budget permit per period and cannot use up the
+ // budget of every other token.
+ match &self.type_budget {
+ Some(budget) if budget.check_key(&warning).is_err() => {
+ ThrottleDecision::TypeBudgetExhausted
+ }
+ _ => ThrottleDecision::Emit,
}
}
@@ -194,4 +244,65 @@ mod tests {
"sweep must free capacity for new keys"
);
}
+
+ #[test]
+ fn type_budget_counts_only_warnings_that_pass_the_per_token_check() {
+ let throttle = WarningThrottle::default()
+ .with_type_budget(DEFAULT_THROTTLE_PERIOD, NonZeroU32::new(2).unwrap());
+ let decisions: Vec<_> = [
+ ("tok_a", WarningType::InvalidOptions),
+ ("tok_a", WarningType::InvalidOptions),
+ ("tok_b", WarningType::InvalidOptions),
+ ("tok_c", WarningType::InvalidOptions),
+ ("tok_c", WarningType::InvalidOptions),
+ ("tok_c", WarningType::MissingEventName),
+ ]
+ .into_iter()
+ .map(|(token, warning)| throttle.check(token, warning))
+ .collect();
+ assert_eq!(
+ decisions,
+ vec![
+ ThrottleDecision::Emit,
+ // A repeat is stopped per token and leaves the budget alone.
+ ThrottleDecision::Throttled,
+ ThrottleDecision::Emit,
+ ThrottleDecision::TypeBudgetExhausted,
+ // The refused check still spent tok_c's per-token permit.
+ ThrottleDecision::Throttled,
+ // Each type has its own budget.
+ ThrottleDecision::Emit,
+ ]
+ );
+ }
+
+ #[test]
+ fn type_budget_refills_after_the_period() {
+ let throttle =
+ WarningThrottle::default().with_type_budget(Duration::from_millis(50), NonZeroU32::MIN);
+ assert_eq!(
+ throttle.check("tok_a", WarningType::InvalidOptions),
+ ThrottleDecision::Emit
+ );
+ assert_eq!(
+ throttle.check("tok_b", WarningType::InvalidOptions),
+ ThrottleDecision::TypeBudgetExhausted
+ );
+ std::thread::sleep(Duration::from_millis(80));
+ assert_eq!(
+ throttle.check("tok_c", WarningType::InvalidOptions),
+ ThrottleDecision::Emit
+ );
+ }
+
+ #[test]
+ fn default_throttle_has_no_type_budget() {
+ let throttle = WarningThrottle::default();
+ for i in 0..1_000 {
+ assert_eq!(
+ throttle.check(&format!("tok_{i}"), WarningType::InvalidOptions),
+ ThrottleDecision::Emit
+ );
+ }
+ }
}
diff --git a/rust/personhog-leader/src/warnings.rs b/rust/personhog-leader/src/warnings.rs
index a199fbf76a54..64116ddbc537 100644
--- a/rust/personhog-leader/src/warnings.rs
+++ b/rust/personhog-leader/src/warnings.rs
@@ -6,7 +6,7 @@ use tracing::warn;
use common_ingestion_warnings::registry::WarningType;
use common_ingestion_warnings::serializer::Warning as WarningPayload;
-use common_ingestion_warnings::throttle::{ThrottleDecision, WarningThrottle};
+use common_ingestion_warnings::throttle::WarningThrottle;
use common_ingestion_warnings::WarningSource;
use common_kafka::kafka_producer::KafkaContext;
@@ -72,27 +72,17 @@ impl WarningsProducer {
pub fn emit(&self, warning: &SizeViolationWarning) {
let warning_type = WarningType::PersonPropertiesSizeViolation;
- match self
+ if let Some(outcome) = self
.throttle
.check(&warning.team_id.to_string(), warning_type)
+ .drop_outcome()
{
- ThrottleDecision::Emit => {}
- ThrottleDecision::Throttled => {
- counter!(
- "personhog_leader_ingestion_warnings_suppressed_total",
- "outcome" => "throttled"
- )
- .increment(1);
- return;
- }
- ThrottleDecision::CardinalityCapped => {
- counter!(
- "personhog_leader_ingestion_warnings_suppressed_total",
- "outcome" => "cardinality_capped"
- )
- .increment(1);
- return;
- }
+ counter!(
+ "personhog_leader_ingestion_warnings_suppressed_total",
+ "outcome" => outcome
+ )
+ .increment(1);
+ return;
}
// teamId, category, severity, and pipelineStep are injected by the