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(property-vals): add two-stage aggregation to collapse pod amplification (#60309)

Andy Zhaoba90f76d0c22
diff --git a/rust/property-vals-rs/src/config.rs b/rust/property-vals-rs/src/config.rs
index c5a80da4bbc3..efc33680e39c 100644
--- a/rust/property-vals-rs/src/config.rs
+++ b/rust/property-vals-rs/src/config.rs
@@ -23,6 +23,12 @@ pub struct Config {
#[envconfig(default = "clickhouse_property_values")]
pub output_topic: String,
+ #[envconfig(default = "property_vals_intermediate")]
+ pub intermediate_topic: String,
+
+ #[envconfig(default = "clickhouse-property-vals-rs-merger")]
+ pub merger_consumer_group: String,
+
#[envconfig(default = "30")]
pub flush_interval_secs: u64,
diff --git a/rust/property-vals-rs/src/fan_out.rs b/rust/property-vals-rs/src/fan_out.rs
index f79e83f5692a..6f8d71a5b5b2 100644
--- a/rust/property-vals-rs/src/fan_out.rs
+++ b/rust/property-vals-rs/src/fan_out.rs
@@ -1,12 +1,12 @@
use serde_json::Value;
use crate::config::ExcludedPropertyKeys;
-use crate::types::{Event, GroupIdentify, PropertyType, TupleKey};
+use crate::types::{Event, GroupIdentify, PropertyType, PropertyValueMessage, TupleKey};
pub const MAX_PROPERTY_KEY_LEN: usize = 400;
pub const MAX_PROPERTY_VALUE_LEN: usize = 255;
-pub fn fan_out(event: &Event, excluded: &ExcludedPropertyKeys) -> Vec<TupleKey> {
+pub fn fan_out(event: &Event, excluded: &ExcludedPropertyKeys) -> Vec<(TupleKey, u64)> {
let mut out = Vec::new();
if let Some(raw) = &event.properties {
@@ -19,7 +19,10 @@ pub fn fan_out(event: &Event, excluded: &ExcludedPropertyKeys) -> Vec<TupleKey>
out
}
-pub fn fan_out_group(event: &GroupIdentify, excluded: &ExcludedPropertyKeys) -> Vec<TupleKey> {
+pub fn fan_out_group(
+ event: &GroupIdentify,
+ excluded: &ExcludedPropertyKeys,
+) -> Vec<(TupleKey, u64)> {
let mut out = Vec::new();
if let Some(raw) = &event.group_properties {
emit_from_blob(
@@ -33,12 +36,27 @@ pub fn fan_out_group(event: &GroupIdentify, excluded: &ExcludedPropertyKeys) ->
out
}
+pub fn extract_tuple(msg: &PropertyValueMessage) -> Vec<(TupleKey, u64)> {
+ if msg.property_key.is_empty() || msg.property_value.is_empty() {
+ return Vec::new();
+ }
+ vec![(
+ TupleKey {
+ team_id: msg.team_id,
+ property_type: msg.property_type,
+ property_key: msg.property_key.clone(),
+ property_value: msg.property_value.clone(),
+ },
+ msg.property_count,
+ )]
+}
+
fn emit_from_blob(
team_id: i64,
property_type: PropertyType,
raw: &str,
excluded: &ExcludedPropertyKeys,
- out: &mut Vec<TupleKey>,
+ out: &mut Vec<(TupleKey, u64)>,
) {
let parsed: Value = match serde_json::from_str(raw) {
Ok(v) => v,
@@ -68,12 +86,15 @@ fn emit_from_blob(
continue;
}
- out.push(TupleKey {
- team_id,
- property_type,
- property_key: key.clone(),
- property_value,
- });
+ out.push((
+ TupleKey {
+ team_id,
+ property_type,
+ property_key: key.clone(),
+ property_value,
+ },
+ 1,
+ ));
}
}
@@ -156,26 +177,27 @@ mod tests {
keys.join(",").parse().unwrap()
}
- fn check_tuple_invariants(t: &TupleKey, expected_team: i64) {
+ fn check_tuple_invariants(t: &TupleKey, count: u64, expected_team: i64) {
assert_eq!(t.team_id, expected_team);
assert!(!t.property_key.is_empty());
assert!(!t.property_value.is_empty());
assert!(t.property_key.chars().count() <= MAX_PROPERTY_KEY_LEN);
assert!(t.property_value.chars().count() <= MAX_PROPERTY_VALUE_LEN);
+ assert_eq!(count, 1, "stage-1 fan-out always emits count=1");
}
proptest! {
#[test]
fn fan_out_outputs_obey_caps_and_team(e in arb_event()) {
- for t in fan_out(&e, &none()) {
- check_tuple_invariants(&t, e.team_id);
+ for (t, n) in fan_out(&e, &none()) {
+ check_tuple_invariants(&t, n, e.team_id);
}
}
#[test]
fn fan_out_group_outputs_obey_caps_and_team(g in arb_group_identify()) {
- for t in fan_out_group(&g, &none()) {
- check_tuple_invariants(&t, g.team_id);
+ for (t, n) in fan_out_group(&g, &none()) {
+ check_tuple_invariants(&t, n, g.team_id);
}
}
@@ -191,7 +213,7 @@ mod tests {
#[test]
fn fan_out_group_property_type_matches_index(g in arb_group_identify()) {
- for t in fan_out_group(&g, &none()) {
+ for (t, _) in fan_out_group(&g, &none()) {
prop_assert_eq!(t.property_type, PropertyType::Group(g.group_type_index));
}
}
@@ -201,9 +223,10 @@ mod tests {
fn event_property_produces_event_type_tuple() {
let tuples = fan_out(&event(r#"{"$browser":"Chrome"}"#), &none());
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_type, PropertyType::Event);
- assert_eq!(tuples[0].property_key, "$browser");
- assert_eq!(tuples[0].property_value, "Chrome");
+ assert_eq!(tuples[0].0.property_type, PropertyType::Event);
+ assert_eq!(tuples[0].0.property_key, "$browser");
+ assert_eq!(tuples[0].0.property_value, "Chrome");
+ assert_eq!(tuples[0].1, 1);
}
#[test]
@@ -227,23 +250,23 @@ mod tests {
};
let tuples = fan_out(&ev, &none());
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_type, PropertyType::Person);
- assert_eq!(tuples[0].property_key, "email");
- assert_eq!(tuples[0].property_value, "[email protected]");
+ assert_eq!(tuples[0].0.property_type, PropertyType::Person);
+ assert_eq!(tuples[0].0.property_key, "email");
+ assert_eq!(tuples[0].0.property_value, "[email protected]");
}
#[test]
fn bool_value_coerces_to_string() {
let tuples = fan_out(&event(r#"{"a_bool":true}"#), &none());
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_value, "true");
+ assert_eq!(tuples[0].0.property_value, "true");
}
#[test]
fn number_value_coerces_to_string() {
let tuples = fan_out(&event(r#"{"a_number":42}"#), &none());
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_value, "42");
+ assert_eq!(tuples[0].0.property_value, "42");
}
#[test]
@@ -262,16 +285,16 @@ mod tests {
fn group_identify_index_0_emits_group_type() {
let tuples = fan_out_group(&group_identify(0, r#"{"plan":"enterprise"}"#), &none());
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_type, PropertyType::Group(0));
- assert_eq!(tuples[0].property_key, "plan");
- assert_eq!(tuples[0].property_value, "enterprise");
+ assert_eq!(tuples[0].0.property_type, PropertyType::Group(0));
+ assert_eq!(tuples[0].0.property_key, "plan");
+ assert_eq!(tuples[0].0.property_value, "enterprise");
}
#[test]
fn group_identify_emits_group_type_matching_index() {
let tuples = fan_out_group(&group_identify(4, r#"{"region":"us-east"}"#), &none());
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_type, PropertyType::Group(4));
+ assert_eq!(tuples[0].0.property_type, PropertyType::Group(4));
}
#[test]
@@ -297,8 +320,8 @@ mod tests {
let exclusions = excluded(&["$insert_id", "distinct_id", "$session_id"]);
let tuples = fan_out(&event(blob), &exclusions);
assert_eq!(tuples.len(), 1, "only $browser should survive exclusion");
- assert_eq!(tuples[0].property_key, "$browser");
- assert_eq!(tuples[0].property_value, "Chrome");
+ assert_eq!(tuples[0].0.property_key, "$browser");
+ assert_eq!(tuples[0].0.property_value, "Chrome");
}
#[test]
@@ -312,7 +335,10 @@ mod tests {
};
let tuples = fan_out(&ev, &excluded(&["$session_id"]));
assert_eq!(tuples.len(), 2);
- let keys: Vec<&str> = tuples.iter().map(|t| t.property_key.as_str()).collect();
+ let keys: Vec<&str> = tuples
+ .iter()
+ .map(|(t, _)| t.property_key.as_str())
+ .collect();
assert!(keys.contains(&"email"));
assert!(keys.contains(&"plan"));
assert!(!keys.contains(&"$session_id"));
@@ -323,7 +349,7 @@ mod tests {
let g = group_identify(0, r#"{"plan":"enterprise","internal_id":"g-42"}"#);
let tuples = fan_out_group(&g, &excluded(&["internal_id"]));
assert_eq!(tuples.len(), 1);
- assert_eq!(tuples[0].property_key, "plan");
+ assert_eq!(tuples[0].0.property_key, "plan");
}
#[test]
@@ -335,4 +361,86 @@ mod tests {
assert_eq!(with_default.len(), 2);
assert_eq!(with_default, with_parsed_empty);
}
+
+ fn pv_message(
+ team_id: i64,
+ property_type: PropertyType,
+ key: &str,
+ value: &str,
+ count: u64,
+ ) -> PropertyValueMessage {
+ PropertyValueMessage {
+ team_id,
+ property_type,
+ property_key: key.to_string(),
+ property_value: value.to_string(),
+ property_count: count,
+ }
+ }
+
+ #[test]
+ fn extract_tuple_emits_single_tuple_with_message_count() {
+ let msg = pv_message(2, PropertyType::Event, "$browser", "Chrome", 42);
+ let out = extract_tuple(&msg);
+ assert_eq!(out.len(), 1);
+ assert_eq!(out[0].0.team_id, 2);
+ assert_eq!(out[0].0.property_type, PropertyType::Event);
+ assert_eq!(out[0].0.property_key, "$browser");
+ assert_eq!(out[0].0.property_value, "Chrome");
+ assert_eq!(out[0].1, 42, "count must round-trip from the message");
+ }
+
+ #[test]
+ fn extract_tuple_carries_property_count_for_person_type() {
+ let msg = pv_message(7, PropertyType::Person, "email", "[email protected]", 5);
+ let out = extract_tuple(&msg);
+ assert_eq!(out[0].0.property_type, PropertyType::Person);
+ assert_eq!(out[0].1, 5);
+ }
+
+ #[test]
+ fn extract_tuple_carries_property_count_for_group_type() {
+ let msg = pv_message(7, PropertyType::Group(3), "plan", "enterprise", 11);
+ let out = extract_tuple(&msg);
+ assert_eq!(out[0].0.property_type, PropertyType::Group(3));
+ assert_eq!(out[0].1, 11);
+ }
+
+ #[test]
+ fn extract_tuple_drops_empty_key_or_value() {
+ let empty_key = pv_message(2, PropertyType::Event, "", "Chrome", 1);
+ assert!(extract_tuple(&empty_key).is_empty());
+ let empty_value = pv_message(2, PropertyType::Event, "$browser", "", 1);
+ assert!(extract_tuple(&empty_value).is_empty());
+ }
+
+ #[test]
+ fn property_value_message_round_trips_producer_wire_format() {
+ use crate::producer::Outgoing;
+ for (pt, expected) in [
+ (PropertyType::Event, "event"),
+ (PropertyType::Person, "person"),
+ (PropertyType::Group(0), "group_0"),
+ (PropertyType::Group(7), "group_7"),
+ ] {
+ let outgoing = Outgoing {
+ team_id: 2,
+ property_type: pt,
+ property_key: "$browser",
+ property_value: "Chrome",
+ property_count: 99,
+ };
+ let serialized = serde_json::to_string(&outgoing).unwrap();
+ assert!(
+ serialized.contains(&format!(r#""property_type":"{expected}""#)),
+ "expected {expected} in {serialized}"
+ );
+ let parsed: PropertyValueMessage = serde_json::from_str(&serialized).unwrap();
+ assert_eq!(parsed.team_id, 2);
+ assert_eq!(parsed.property_type, pt);
+ assert_eq!(parsed.property_key, "$browser");
+ assert_eq!(parsed.property_value, "Chrome");
+ assert_eq!(parsed.property_count, 99);
+ }
+ }
}
diff --git a/rust/property-vals-rs/src/main.rs b/rust/property-vals-rs/src/main.rs
index 6eb84fcf2be2..4f3ecce83c1d 100644
--- a/rust/property-vals-rs/src/main.rs
+++ b/rust/property-vals-rs/src/main.rs
@@ -6,9 +6,9 @@ use common_kafka::kafka_consumer::SingleTopicConsumer;
use lifecycle::{ComponentOptions, Manager};
use property_vals_rs::{
config::Config,
- fan_out::{fan_out, fan_out_group},
+ fan_out::{extract_tuple, fan_out, fan_out_group},
producer::AggregatedProducer,
- types::{Event, GroupIdentify},
+ types::{Event, GroupIdentify, PropertyValueMessage},
worker::worker_loop,
};
use serve_metrics::setup_metrics_routes;
@@ -66,6 +66,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_liveness_deadline(Duration::from_secs(60))
.with_stall_threshold(3),
);
+ let merger_handle = manager.register(
+ "merger-worker",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(30))
+ .with_liveness_deadline(Duration::from_secs(60))
+ .with_stall_threshold(3),
+ );
let metrics_handle =
manager.register("metrics", ComponentOptions::new().is_observability(true));
@@ -78,6 +85,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
events_consumer_group = %config.consumer.kafka_consumer_group,
groups_topic = %config.groups_kafka_consumer_topic,
groups_consumer_group = %config.groups_kafka_consumer_group,
+ intermediate_topic = %config.intermediate_topic,
+ merger_consumer_group = %config.merger_consumer_group,
output_topic = %config.output_topic,
flush_interval_secs = config.flush_interval_secs,
"config loaded"
@@ -89,7 +98,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let events_producer = AggregatedProducer::new(
&config.kafka,
events_handle.clone(),
- config.output_topic.clone(),
+ config.intermediate_topic.clone(),
produce_timeout,
)
.await?;
@@ -101,6 +110,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let groups_producer = AggregatedProducer::new(
&config.kafka,
groups_handle.clone(),
+ config.intermediate_topic.clone(),
+ produce_timeout,
+ )
+ .await?;
+
+ let mut merger_consumer_config = config.consumer.clone();
+ merger_consumer_config.kafka_consumer_topic = config.intermediate_topic.clone();
+ merger_consumer_config.kafka_consumer_group = config.merger_consumer_group.clone();
+ let merger_consumer = SingleTopicConsumer::new(config.kafka.clone(), merger_consumer_config)?;
+ let merger_producer = AggregatedProducer::new(
+ &config.kafka,
+ merger_handle.clone(),
config.output_topic.clone(),
produce_timeout,
)
@@ -114,6 +135,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"Subscribed to topic: {}",
config.groups_kafka_consumer_topic
);
+ info!("Subscribed to topic: {}", config.intermediate_topic);
let shared_config = Arc::new(config.clone());
@@ -136,8 +158,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
groups_handle.clone(),
move |g: &GroupIdentify| fan_out_group(g, &excluded_groups),
));
+ tokio::spawn(worker_loop::<PropertyValueMessage, _, _>(
+ shared_config.clone(),
+ merger_consumer,
+ merger_producer,
+ merger_handle.clone(),
+ |m: &PropertyValueMessage| extract_tuple(m),
+ ));
drop(events_handle);
drop(groups_handle);
+ drop(merger_handle);
let app = Router::new()
.route("/", get(index))
diff --git a/rust/property-vals-rs/src/producer.rs b/rust/property-vals-rs/src/producer.rs
index 67af1106d6d6..d1837b01cc74 100644
--- a/rust/property-vals-rs/src/producer.rs
+++ b/rust/property-vals-rs/src/producer.rs
@@ -13,12 +13,12 @@ use tracing::warn;
use crate::types::{PropertyType, TupleKey};
#[derive(serde::Serialize)]
-struct Outgoing<'a> {
- team_id: i64,
- property_type: PropertyType,
- property_key: &'a str,
- property_value: &'a str,
- property_count: u64,
+pub(crate) struct Outgoing<'a> {
+ pub team_id: i64,
+ pub property_type: PropertyType,
+ pub property_key: &'a str,
+ pub property_value: &'a str,
+ pub property_count: u64,
}
#[derive(Debug, Error)]
@@ -84,10 +84,22 @@ impl Producer for AggregatedProducer {
})
.collect();
+ // Full-tuple partition key. The same (team, type, key, value) tuple
+ // from any pod always lands on the same partition, so the merger on
+ // the consuming side can merge the per-pod duplicates that the
+ // events/groups workers emit across replicas.
let send_fut = send_keyed_iter_to_kafka(
&self.inner,
&self.output_topic,
- |m| Some(format!("{}:{}", m.team_id, m.property_key)),
+ |m| {
+ Some(format!(
+ "{}:{}:{}:{}",
+ m.team_id,
+ m.property_type.as_kafka_key_segment(),
+ m.property_key,
+ m.property_value,
+ ))
+ },
messages,
);
diff --git a/rust/property-vals-rs/src/types.rs b/rust/property-vals-rs/src/types.rs
index 020c19db6ab3..7780f9dcf36a 100644
--- a/rust/property-vals-rs/src/types.rs
+++ b/rust/property-vals-rs/src/types.rs
@@ -1,3 +1,4 @@
+use serde::de::{self, Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
pub trait IngestableEvent: serde::de::DeserializeOwned + Send + Sync + 'static {
@@ -49,12 +50,55 @@ pub enum PropertyType {
Group(u8),
}
+impl PropertyType {
+ pub fn as_kafka_key_segment(&self) -> String {
+ match self {
+ PropertyType::Event => "event".to_string(),
+ PropertyType::Person => "person".to_string(),
+ PropertyType::Group(n) => format!("group_{n}"),
+ }
+ }
+}
+
impl Serialize for PropertyType {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- match self {
- PropertyType::Event => serializer.serialize_str("event"),
- PropertyType::Person => serializer.serialize_str("person"),
- PropertyType::Group(n) => serializer.serialize_str(&format!("group_{n}")),
+ serializer.serialize_str(&self.as_kafka_key_segment())
+ }
+}
+
+impl<'de> Deserialize<'de> for PropertyType {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let s: &str = Deserialize::deserialize(deserializer)?;
+ match s {
+ "event" => Ok(PropertyType::Event),
+ "person" => Ok(PropertyType::Person),
+ other => {
+ let n: u8 = other
+ .strip_prefix("group_")
+ .ok_or_else(|| de::Error::custom(format!("invalid property_type: {other}")))?
+ .parse()
+ .map_err(|_| {
+ de::Error::custom(format!("invalid group property_type: {other}"))
+ })?;
+ Ok(PropertyType::Group(n))
+ }
}
}
}
+
+/// Wire format of records on the intermediate topic. Mirrors `Outgoing` in
+/// `producer.rs` so a stage-1 produce round-trips to a stage-2 consume.
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct PropertyValueMessage {
+ pub team_id: i64,
+ pub property_type: PropertyType,
+ pub property_key: String,
+ pub property_value: String,
+ pub property_count: u64,
+}
+
+impl IngestableEvent for PropertyValueMessage {
+ fn team_id(&self) -> i64 {
+ self.team_id
+ }
+}
diff --git a/rust/property-vals-rs/src/worker.rs b/rust/property-vals-rs/src/worker.rs
index 5537714643ee..b559fbf8f4d1 100644
--- a/rust/property-vals-rs/src/worker.rs
+++ b/rust/property-vals-rs/src/worker.rs
@@ -27,7 +27,7 @@ pub async fn worker_loop<E, P, F>(
) where
E: IngestableEvent,
P: Producer,
- F: Fn(&E) -> Vec<TupleKey>,
+ F: Fn(&E) -> Vec<(TupleKey, u64)>,
{
let _guard = handle.process_scope();
@@ -64,8 +64,8 @@ pub async fn worker_loop<E, P, F>(
if config.should_process(event.team_id()) {
let tuples = fan_out_fn(&event);
metrics::counter!(TUPLES_AGGREGATED).increment(tuples.len() as u64);
- for t in tuples {
- aggregator.add(t, 1);
+ for (t, count) in tuples {
+ aggregator.add(t, count);
}
} else {
metrics::counter!(EVENTS_FILTERED).increment(1);