: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(capture): add OverflowLimiter to v1 (#59714)
Eli Reisman766d373818cb
diff --git a/rust/capture/src/v1/analytics/constants.rs b/rust/capture/src/v1/analytics/constants.rsindex 3a66e7461d7d..ba19e277cba1 100644--- a/rust/capture/src/v1/analytics/constants.rs+++ b/rust/capture/src/v1/analytics/constants.rs@@ -48,6 +48,9 @@ pub(super) const CAPTURE_V1_EVENTS_DROPPED: &str = "capture_v1_events_dropped";/// Counter for events marked as quota-limited, labeled by resource bucket.pub(crate) const CAPTURE_V1_EVENTS_QUOTA_LIMITED: &str = "capture_v1_events_quota_limited";+/// Counter for events rerouted to the overflow topic by the burst limiter.+pub(super) const CAPTURE_V1_OVERFLOW_ROUTED: &str = "capture_v1_events_rerouted_overflow";+/// Counter/gauge key for the per-token global rate limiter.pub(crate) const CAPTURE_V1_RATE_LIMITER: &str = "capture_v1_rate_limiter";diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex 1aacd4fbb2ae..79e2f1864c44 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -6,18 +6,21 @@ use uuid::Uuid;use super::constants::{CAPTURE_V1_DISTINCT_ID_MAX_SIZE, CAPTURE_V1_EVENTS_DROPPED,CAPTURE_V1_EVENTS_REROUTED_HISTORICAL, CAPTURE_V1_MAX_EVENT_NAME_LENGTH,- CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_RATE_LIMITER, DETAIL_EVENT_RESTRICTION_DROP,- DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS, ILLEGAL_DISTINCT_IDS,+ CAPTURE_V1_OVERFLOW_ROUTED, CAPTURE_V1_PARSED_EVENTS, CAPTURE_V1_RATE_LIMITER,+ DETAIL_EVENT_RESTRICTION_DROP, DETAIL_PERSON_PROCESSING_DISABLED, FUTURE_EVENT_HOURS_CUTOFF_MS,+ ILLEGAL_DISTINCT_IDS,};use super::response::Response;use super::types::{Batch, Event, EventResult, WrappedEvent};use crate::event_restrictions::{EventContext, EventRestrictionService};use crate::global_rate_limiter::{GlobalRateLimitKey, GlobalRateLimiter};use crate::v0_request::DataType;+use limiters::overflow::{OverflowLimiter, OverflowLimiterResult};use tracing::Level;use crate::router;use crate::v1::context::Context;+use crate::v1::sinks::event::Event as SinkEvent;use crate::v1::sinks::Destination;use crate::v1::Error;@@ -62,6 +65,12 @@ pub async fn process_batch(apply_historical_rerouting(&state.historical_cfg, context, &mut events);+ // Overflow and global rate limit are independent checks on different axes:+ // overflow reroutes bursting keys; global rate limit disables person processing.+ if let Some(ref limiter) = state.overflow_limiter {+ apply_overflow_stamping(limiter, context, &mut events);+ }+if let Some(ref limiter) = state.global_rate_limiter_token_distinctid {apply_token_distinct_id_limits(limiter, context, &mut events).await;}@@ -259,6 +268,42 @@ fn apply_historical_rerouting(}}+fn apply_overflow_stamping(limiter: &OverflowLimiter, ctx: &Context, events: &mut [WrappedEvent]) {+ let mut buf = String::with_capacity(128);++ for event in events.iter_mut() {+ if event.destination != Destination::AnalyticsMain {+ continue;+ }+ if event.result == EventResult::Drop {+ continue;+ }++ buf.clear();+ event.partition_key(ctx, &mut buf);++ match limiter.is_limited(&buf) {+ OverflowLimiterResult::ForceLimited => {+ event.destination = Destination::Overflow;+ // Disables person processing AND nulls partition key at sink.+ event.force_disable_person_processing = true;+ metrics::counter!(CAPTURE_V1_OVERFLOW_ROUTED, "reason" => "force_limited")+ .increment(1);+ }+ OverflowLimiterResult::Limited => {+ event.destination = Destination::Overflow;+ if !limiter.should_preserve_locality() {+ // Nulls partition key at sink -- spreads across partitions.+ event.force_disable_person_processing = true;+ }+ metrics::counter!(CAPTURE_V1_OVERFLOW_ROUTED, "reason" => "rate_limited")+ .increment(1);+ }+ OverflowLimiterResult::NotLimited => {}+ }+ }+}+async fn apply_restrictions(service: &EventRestrictionService,token: &str,@@ -331,6 +376,7 @@ async fn apply_token_distinct_id_limits(.to_cache_key();if limiter.is_limited(&cache_key, 1).await.is_some() {event.result = EventResult::Limited;+ // Disables person processing -- sink will null partition key for Main/Overflow.event.force_disable_person_processing = true;event.details = Some(DETAIL_PERSON_PROCESSING_DISABLED);limited_distinct_ids.insert(event.event.distinct_id.as_str());@@ -1658,4 +1704,130 @@ mod tests {"order changed after apply_token_distinct_id_limits",);}++ // --- apply_overflow_stamping ---++ fn overflow_limiter(per_second: u32, burst: u32, force_keys: Option<&str>) -> OverflowLimiter {+ use std::num::NonZeroU32;+ OverflowLimiter::new(+ NonZeroU32::new(per_second).unwrap(),+ NonZeroU32::new(burst).unwrap(),+ force_keys.map(String::from),+ false,+ )+ }++ fn overflow_limiter_preserving(per_second: u32, burst: u32) -> OverflowLimiter {+ use std::num::NonZeroU32;+ OverflowLimiter::new(+ NonZeroU32::new(per_second).unwrap(),+ NonZeroU32::new(burst).unwrap(),+ None,+ true,+ )+ }++ #[test]+ fn overflow_not_limited() {+ let ctx = test_utils::test_context();+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ let limiter = overflow_limiter(100, 100, None);++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(events[0].destination, Destination::AnalyticsMain);+ assert!(!events[0].force_disable_person_processing);+ }++ #[test]+ fn overflow_force_limited_by_full_key() {+ let mut ctx = test_utils::test_context();+ ctx.api_token = "phc_tok".to_string();+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ let limiter = overflow_limiter(100, 100, Some("phc_tok:user-1"));++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(events[0].destination, Destination::Overflow);+ assert!(events[0].force_disable_person_processing);+ }++ #[test]+ fn overflow_force_limited_by_token_only() {+ let mut ctx = test_utils::test_context();+ ctx.api_token = "phc_tok".to_string();+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ let limiter = overflow_limiter(100, 100, Some("phc_tok"));++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(events[0].destination, Destination::Overflow);+ assert!(events[0].force_disable_person_processing);+ }++ #[test]+ fn overflow_rate_limited_disables_person_processing() {+ let mut ctx = test_utils::test_context();+ ctx.api_token = "phc_tok".to_string();+ // burst=1 means only 1 event allowed, the second will be limited+ let limiter = overflow_limiter(1, 1, None);+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-1"),+ ];++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(events[0].destination, Destination::AnalyticsMain);+ assert!(!events[0].force_disable_person_processing);+ assert_eq!(events[1].destination, Destination::Overflow);+ assert!(events[1].force_disable_person_processing);+ }++ #[test]+ fn overflow_rate_limited_preserves_locality_when_configured() {+ let mut ctx = test_utils::test_context();+ ctx.api_token = "phc_tok".to_string();+ let limiter = overflow_limiter_preserving(1, 1);+ let mut events = vec![+ wrapped_event("$pageview", "user-1"),+ wrapped_event("$pageview", "user-1"),+ ];++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(events[1].destination, Destination::Overflow);+ assert!(+ !events[1].force_disable_person_processing,+ "preserve_locality=true means person processing stays enabled"+ );+ }++ #[test]+ fn overflow_skips_non_analytics_main() {+ let ctx = test_utils::test_context();+ let limiter = overflow_limiter(100, 100, Some("phc_test_token:user-1"));+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ events[0].destination = Destination::AnalyticsHistorical;++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(+ events[0].destination,+ Destination::AnalyticsHistorical,+ "non-AnalyticsMain events are not overflow-checked"+ );+ }++ #[test]+ fn overflow_skips_dropped_events() {+ let ctx = test_utils::test_context();+ let limiter = overflow_limiter(100, 100, Some("phc_test_token:user-1"));+ let mut events = vec![wrapped_event("$pageview", "user-1")];+ events[0].result = EventResult::Drop;++ apply_overflow_stamping(&limiter, &ctx, &mut events);++ assert_eq!(events[0].destination, Destination::AnalyticsMain);+ }}diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rsindex bfc914ecafc7..12ac777b0eec 100644--- a/rust/capture/src/v1/analytics/types.rs+++ b/rust/capture/src/v1/analytics/types.rs@@ -176,19 +176,8 @@ impl SinkEvent for WrappedEvent {}}- fn partition_key<'buf>(&self, ctx: &Context, buf: &'buf mut String) -> Option<&'buf str> {+ fn partition_key(&self, ctx: &Context, buf: &mut String) {use std::fmt::Write;- // v0 parity: only drop partition key for main/overflow analytics.- // DLQ, Historical, and Custom destinations always retain their key- // even when person processing is disabled via event restrictions.- if self.force_disable_person_processing- && matches!(- self.destination,- Destination::AnalyticsMain | Destination::Overflow- )- {- return None;- }match (self.event.options.cookieless_mode == Some(true),ctx.capture_internal,@@ -203,7 +192,6 @@ impl SinkEvent for WrappedEvent {let _ = write!(buf, "{}:{}", ctx.api_token, self.event.distinct_id);}}- Some(buf.as_str())}fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()> {@@ -880,9 +868,10 @@ mod tests {assert!(h.historical_migration.is_none());}- fn partition_key_str(ev: &WrappedEvent, ctx: &Context) -> Option<String> {+ fn partition_key_str(ev: &WrappedEvent, ctx: &Context) -> String {let mut buf = String::new();- ev.partition_key(ctx, &mut buf).map(String::from)+ ev.partition_key(ctx, &mut buf);+ buf}#[test]@@ -891,7 +880,7 @@ mod tests {let ev = ok_wrapped("$pageview", "user-42");assert_eq!(partition_key_str(&ev, &ctx),- Some(format!("{}:user-42", ctx.api_token))+ format!("{}:user-42", ctx.api_token));}@@ -902,7 +891,7 @@ mod tests {ev.event.options.cookieless_mode = Some(true);assert_eq!(partition_key_str(&ev, &ctx),- Some(format!("{}:{}", ctx.api_token, ctx.client_ip))+ format!("{}:{}", ctx.api_token, ctx.client_ip));}@@ -914,7 +903,7 @@ mod tests {ev.event.options.cookieless_mode = Some(true);assert_eq!(partition_key_str(&ev, &ctx),- Some(format!("{}:127.0.0.1", ctx.api_token))+ format!("{}:127.0.0.1", ctx.api_token));}@@ -925,72 +914,16 @@ mod tests {assert_eq!(*ev.destination(), Destination::Overflow);}- // --- partition key + force_disable_person_processing × destination ----#[test]- fn partition_key_force_disable_analytics_main() {+ fn partition_key_always_writes_regardless_of_force_disable() {let ctx = test_utils::test_context();let mut ev = ok_wrapped("$pageview", "user-42");ev.force_disable_person_processing = true;ev.destination = Destination::AnalyticsMain;- assert_eq!(partition_key_str(&ev, &ctx), None);- }-- #[test]- fn partition_key_force_disable_overflow() {- let ctx = test_utils::test_context();- let mut ev = ok_wrapped("$pageview", "user-42");- ev.force_disable_person_processing = true;- ev.destination = Destination::Overflow;- assert_eq!(partition_key_str(&ev, &ctx), None);- }-- #[test]- fn partition_key_force_disable_dlq() {- let ctx = test_utils::test_context();- let mut ev = ok_wrapped("$pageview", "user-42");- ev.force_disable_person_processing = true;- ev.destination = Destination::Dlq;- assert_eq!(- partition_key_str(&ev, &ctx),- Some(format!("{}:user-42", ctx.api_token))- );- }-- #[test]- fn partition_key_force_disable_historical() {- let ctx = test_utils::test_context();- let mut ev = ok_wrapped("$pageview", "user-42");- ev.force_disable_person_processing = true;- ev.destination = Destination::AnalyticsHistorical;- assert_eq!(- partition_key_str(&ev, &ctx),- Some(format!("{}:user-42", ctx.api_token))- );- }-- #[test]- fn partition_key_force_disable_custom() {- let ctx = test_utils::test_context();- let mut ev = ok_wrapped("$pageview", "user-42");- ev.force_disable_person_processing = true;- ev.destination = Destination::Custom("my_topic".into());- assert_eq!(- partition_key_str(&ev, &ctx),- Some(format!("{}:user-42", ctx.api_token))- );- }-- #[test]- fn partition_key_force_disable_cookieless_dlq() {- let ctx = test_utils::test_context();- let mut ev = ok_wrapped("$pageview", "user-42");- ev.force_disable_person_processing = true;- ev.destination = Destination::Dlq;- ev.event.options.cookieless_mode = Some(true);assert_eq!(partition_key_str(&ev, &ctx),- Some(format!("{}:{}", ctx.api_token, ctx.client_ip))+ format!("{}:user-42", ctx.api_token),+ "partition_key() is unconditional; sink applies null-key policy");}diff --git a/rust/capture/src/v1/sinks/event.rs b/rust/capture/src/v1/sinks/event.rsindex 04d80c9eead8..2fba52ed82cc 100644--- a/rust/capture/src/v1/sinks/event.rs+++ b/rust/capture/src/v1/sinks/event.rs@@ -27,10 +27,10 @@ pub trait Event: Send + Sync {/// `common_types`).fn headers(&self, ctx: &Context) -> CapturedEventHeaders;- /// Resolve the partition key for this message into the supplied buffer.- /// Returns `Some(key)` for consistent routing, `None` to let the- /// transport decide (e.g. round-robin across partitions).- fn partition_key<'buf>(&self, ctx: &Context, buf: &'buf mut String) -> Option<&'buf str>;+ /// Write the partition key for this event into `buf`.+ /// Always writes unconditionally -- the sink decides whether to use it+ /// or null it based on routing policy (e.g. force_disable_person_processing).+ fn partition_key(&self, ctx: &Context, buf: &mut String);/// Serialize the event payload into a caller-provided buffer.fn serialize_into(&self, ctx: &Context, buf: &mut String) -> anyhow::Result<()>;diff --git a/rust/capture/src/v1/sinks/kafka/sink.rs b/rust/capture/src/v1/sinks/kafka/sink.rsindex 8fb50a3f14c4..808a78438fae 100644--- a/rust/capture/src/v1/sinks/kafka/sink.rs+++ b/rust/capture/src/v1/sinks/kafka/sink.rs@@ -16,13 +16,33 @@ use crate::config::CaptureMode;use crate::v1::context::Context;use crate::v1::sinks::event::Event;use crate::v1::sinks::sink::Sink;-use crate::v1::sinks::types::{BatchSummary, Outcome, SinkResult};+use crate::v1::sinks::types::{BatchSummary, Destination, Outcome, SinkResult};use crate::v1::sinks::{Config, SinkName};use super::producer::ProduceRecord;use super::types::{KafkaResult, KafkaSinkError};use super::KafkaProducerTrait;+/// Null the partition key when person processing is force-disabled for+/// Main/Overflow destinations — spreads load across partitions instead of+/// hotspotting on a single token:distinct_id pair.+fn effective_partition_key<'a>(+ key_buf: &'a str,+ force_disable_person_processing: bool,+ destination: &Destination,+) -> Option<&'a str> {+ if force_disable_person_processing+ && matches!(+ destination,+ Destination::AnalyticsMain | Destination::Overflow+ )+ {+ None+ } else {+ Some(key_buf)+ }+}+/// Shared label values for metrics emitted within a single `publish_batch` call./// All fields are `&'static str` (zero-cost) or `SharedString` (Arc-based, so/// `.clone()` is a refcount bump rather than a heap allocation).@@ -158,10 +178,19 @@ impl<P: KafkaProducerTrait + 'static> KafkaSink<P> {continue;}- let headers: rdkafka::message::OwnedHeaders = event.headers(ctx).into();+ let captured_headers = event.headers(ctx);key_buf.clear();- let key = event.partition_key(ctx, &mut key_buf);+ event.partition_key(ctx, &mut key_buf);+ let key = effective_partition_key(+ &key_buf,+ captured_headers+ .force_disable_person_processing+ .unwrap_or(false),+ event.destination(),+ );++ let headers: rdkafka::message::OwnedHeaders = captured_headers.into();let mut record = ProduceRecord {topic,@@ -447,3 +476,24 @@ impl<P: KafkaProducerTrait + 'static> Sink for KafkaSink<P> {.map_err(|e| anyhow::anyhow!("flush task panicked: {e:#}"))?}}++#[cfg(test)]+mod effective_partition_key_tests {+ use super::*;+ use rstest::rstest;++ #[rstest]+ #[case::main_disabled(true, Destination::AnalyticsMain, None)]+ #[case::overflow_disabled(true, Destination::Overflow, None)]+ #[case::dlq_disabled(true, Destination::Dlq, Some("k"))]+ #[case::historical_disabled(true, Destination::AnalyticsHistorical, Some("k"))]+ #[case::custom_disabled(true, Destination::Custom("t".into()), Some("k"))]+ #[case::main_not_disabled(false, Destination::AnalyticsMain, Some("k"))]+ fn policy(+ #[case] force_disable: bool,+ #[case] dest: Destination,+ #[case] expected: Option<&str>,+ ) {+ assert_eq!(effective_partition_key("k", force_disable, &dest), expected);+ }+}diff --git a/rust/capture/src/v1/sinks/kafka/sink_tests.rs b/rust/capture/src/v1/sinks/kafka/sink_tests.rsindex b22da54a66e5..99759c19dba8 100644--- a/rust/capture/src/v1/sinks/kafka/sink_tests.rs+++ b/rust/capture/src/v1/sinks/kafka/sink_tests.rs@@ -83,6 +83,11 @@ impl FakeEvent {self.partition_key = k.map(String::from);self}++ fn with_headers(mut self, h: CapturedEventHeaders) -> Self {+ self.event_headers = h;+ self+ }}impl Event for FakeEvent {@@ -102,13 +107,9 @@ impl Event for FakeEvent {self.event_headers.clone()}- fn partition_key<'buf>(&self, _ctx: &Context, buf: &'buf mut String) -> Option<&'buf str> {- match &self.partition_key {- Some(k) => {- buf.push_str(k);- Some(buf.as_str())- }- None => None,+ fn partition_key(&self, _ctx: &Context, buf: &mut String) {+ if let Some(k) = &self.partition_key {+ buf.push_str(k);}}@@ -883,13 +884,31 @@ async fn health_refreshed_on_partial_success() {}// ----------------------------------------------------------------------------// Partition key: None vs Some+// Partition key: null-key policy × destination// ---------------------------------------------------------------------------+#[rstest]+#[case::analytics_main(Destination::AnalyticsMain, true, None)]+#[case::overflow(Destination::Overflow, true, None)]+#[case::dlq(Destination::Dlq, true, Some("phc_test:user-1"))]+#[case::historical(Destination::AnalyticsHistorical, true, Some("phc_test:user-1"))]+#[case::custom(Destination::Custom("my_topic".into()), true, Some("phc_test:user-1"))]+#[case::analytics_main_no_disable(Destination::AnalyticsMain, false, Some("phc_test:user-1"))]#[tokio::test]-async fn none_partition_key_propagates_as_none() {+async fn force_disable_null_key_policy(+ #[case] destination: Destination,+ #[case] force_disable: bool,+ #[case] expected_key: Option<&str>,+) {let h = TestHarness::new();- let event = FakeEvent::ok("evt-1").with_partition_key(None);+ let mut headers = empty_captured_headers();+ if force_disable {+ headers.force_disable_person_processing = Some(true);+ }+ let event = FakeEvent::ok("evt-1")+ .with_partition_key(Some("phc_test:user-1"))+ .with_destination(destination)+ .with_headers(headers);let events: Vec<&(dyn Event + Send + Sync)> = vec![&event];let results = h.sink.publish_batch(&h.ctx, &events).await;@@ -897,10 +916,7 @@ async fn none_partition_key_propagates_as_none() {assert_eq!(results.len(), 1);assert_eq!(results[0].outcome(), Outcome::Success);h.producer.with_records(|records| {- assert_eq!(- records[0].key, None,- "None partition key must propagate as None"- );+ assert_eq!(records[0].key.as_deref(), expected_key);});}diff --git a/rust/capture/src/v1/sinks/router.rs b/rust/capture/src/v1/sinks/router.rsindex bf702c163da3..fa0b1b43e0cd 100644--- a/rust/capture/src/v1/sinks/router.rs+++ b/rust/capture/src/v1/sinks/router.rs@@ -177,10 +177,9 @@ mod tests {dlq_timestamp: None,}}- fn partition_key<'buf>(&self, _ctx: &Context, buf: &'buf mut String) -> Option<&'buf str> {+ fn partition_key(&self, _ctx: &Context, buf: &mut String) {use std::fmt::Write;let _ = write!(buf, "key:{}", self.uuid());- Some(buf.as_str())}fn serialize_into(&self, _ctx: &Context, buf: &mut String) -> anyhow::Result<()> {buf.push_str(r#"{"event":"test"}"#);diff --git a/rust/common/limiters/src/overflow.rs b/rust/common/limiters/src/overflow.rsindex 30702a7103af..7861f40a35d9 100644--- a/rust/common/limiters/src/overflow.rs+++ b/rust/common/limiters/src/overflow.rs@@ -66,7 +66,7 @@ impl OverflowLimiter {}// is the event key in the forced_keys list?- if self.keys_to_reroute.contains(event_key) {+ if self.keys_to_reroute.contains(event_key.as_str()) {return OverflowLimiterResult::ForceLimited;}