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.

perf(propdefs): cut per-update overhead in the hot ingestion path (#94374)

José Sequeira5d142534fc57
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 161aaafe2f93..a117e2f09e6d 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -9553,6 +9553,7 @@ name = "property-defs-rs"
version = "0.1.0"
dependencies = [
"ahash 0.8.12",
+ "aho-corasick",
"anyhow",
"axum 0.7.9",
"chrono",
diff --git a/rust/property-defs-rs/Cargo.toml b/rust/property-defs-rs/Cargo.toml
index 530d604023b4..304692e991ad 100644
--- a/rust/property-defs-rs/Cargo.toml
+++ b/rust/property-defs-rs/Cargo.toml
@@ -30,6 +30,7 @@ anyhow = { workspace = true }
personhog-proto = { path = "../personhog-proto" }
tonic = { workspace = true }
thiserror.workspace = true
+aho-corasick.workspace = true
regex.workspace = true
[dev-dependencies]
diff --git a/rust/property-defs-rs/src/lib.rs b/rust/property-defs-rs/src/lib.rs
index 1ed7dec61dff..cff466981559 100644
--- a/rust/property-defs-rs/src/lib.rs
+++ b/rust/property-defs-rs/src/lib.rs
@@ -154,6 +154,16 @@ pub async fn update_producer_loop(
let mut batch = AHashSet::with_capacity(config.compaction_batch_size);
let mut last_send = tokio::time::Instant::now();
let drain_interval = Duration::from_secs(config.producer_drain_interval_secs);
+
+ // These fire per event or per update, so resolve the handles once instead of
+ // paying a registry lookup (hash + CAS + handle drop) on every increment.
+ // Safe only because main installs the metrics recorder before spawning us.
+ let events_received = metrics::counter!(EVENTS_RECEIVED);
+ let updates_seen = metrics::counter!(UPDATES_SEEN);
+ let updates_per_event = metrics::histogram!(UPDATES_PER_EVENT);
+ let compacted_updates = metrics::counter!(COMPACTED_UPDATES);
+ let updates_filtered_by_cache = metrics::counter!(UPDATES_FILTERED_BY_CACHE);
+ let skipped_due_to_team_filter = metrics::counter!(SKIPPED_DUE_TO_TEAM_FILTER);
loop {
// The timer arm is what lets the flush check at the bottom of the loop run while no
// events are arriving. Without it the loop parks in json_recv(), so a partial compaction
@@ -209,7 +219,7 @@ pub async fn update_producer_loop(
.filter_mode
.should_process(&config.filtered_teams.teams, event.team_id)
{
- metrics::counter!(SKIPPED_DUE_TO_TEAM_FILTER).increment(1);
+ skipped_due_to_team_filter.increment(1);
continue;
}
@@ -218,16 +228,16 @@ pub async fn update_producer_loop(
config.eventdef_last_seen_floor_secs,
);
- metrics::counter!(EVENTS_RECEIVED).increment(1);
- metrics::counter!(UPDATES_SEEN).increment(updates.len() as u64);
- metrics::histogram!(UPDATES_PER_EVENT).record(updates.len() as f64);
+ events_received.increment(1);
+ updates_seen.increment(updates.len() as u64);
+ updates_per_event.record(updates.len() as f64);
for update in updates {
- if batch.contains(&update) {
- metrics::counter!(COMPACTED_UPDATES).increment(1);
- continue;
+ // insert returns false on duplicates, so one hash covers the
+ // membership check and the insert.
+ if !batch.insert(update) {
+ compacted_updates.increment(1);
}
- batch.insert(update);
}
}
@@ -242,7 +252,7 @@ pub async fn update_producer_loop(
for update in batch.drain() {
if shared_cache.contains_key(&update) {
// kept for back-compat; equivalent to sum(prop_defs_cache_hits)
- metrics::counter!(UPDATES_FILTERED_BY_CACHE).increment(1);
+ updates_filtered_by_cache.increment(1);
continue;
}
diff --git a/rust/property-defs-rs/src/main.rs b/rust/property-defs-rs/src/main.rs
index 73724c4464cd..a7ba0e55b881 100644
--- a/rust/property-defs-rs/src/main.rs
+++ b/rust/property-defs-rs/src/main.rs
@@ -110,6 +110,35 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.consumer.kafka_consumer_topic
);
+ // Build HTTP server with lifecycle readiness/liveness. This must happen before the
+ // cache is built and the worker loops are spawned: setup_metrics_routes_with_overrides
+ // installs the global metrics recorder, and those components resolve counter handles
+ // once at startup. A handle resolved before the recorder exists is a no-op forever.
+ let app = Router::new()
+ .route("/", get(index))
+ .route(
+ "/_readiness",
+ get({
+ let r = readiness.clone();
+ move || {
+ let r = r.clone();
+ async move { r.check().await }
+ }
+ }),
+ )
+ .route(
+ "/_liveness",
+ get({
+ let l = liveness.clone();
+ move || {
+ let l = l.clone();
+ async move { l.check().into_response() }
+ }
+ }),
+ );
+ let app = apply_routes(app, context.clone());
+ let app = setup_metrics_routes_with_overrides(app, &bucket_overrides());
+
let (tx, rx) = measuring_channel(config.update_batch_size * config.channel_slots_per_worker);
let cache = Cache::new(
@@ -159,32 +188,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
consumer_handle,
));
- // Build HTTP server with lifecycle readiness/liveness
- let app = Router::new()
- .route("/", get(index))
- .route(
- "/_readiness",
- get({
- let r = readiness.clone();
- move || {
- let r = r.clone();
- async move { r.check().await }
- }
- }),
- )
- .route(
- "/_liveness",
- get({
- let l = liveness.clone();
- move || {
- let l = l.clone();
- async move { l.check().into_response() }
- }
- }),
- );
- let app = apply_routes(app, context);
- let app = setup_metrics_routes_with_overrides(app, &bucket_overrides());
-
let bind = format!("{}:{}", config.host, config.port);
info!(address = %bind, "HTTP server starting");
let listener = TcpListener::bind(&bind).await?;
diff --git a/rust/property-defs-rs/src/types.rs b/rust/property-defs-rs/src/types.rs
index 2eb079602d23..4a4fb8f2338d 100644
--- a/rust/property-defs-rs/src/types.rs
+++ b/rust/property-defs-rs/src/types.rs
@@ -1,5 +1,6 @@
use std::{borrow::Cow, fmt, hash::Hash, str::FromStr, sync::LazyLock};
+use aho_corasick::AhoCorasick;
use chrono::{DateTime, Utc};
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
@@ -78,15 +79,14 @@ pub const SKIP_PROPERTIES: [&str; 9] = [
// rare cases it arrives as a top-level event property, and carries little cardinality weight.
pub const SKIP_EVENT_PROPERTY_PREFIXES: [&str; 2] = ["$feature/", "$feature_enrollment/"];
-const DATETIME_PROPERTY_NAME_KEYWORDS: [&str; 7] = [
- "time",
- "timestamp",
- "date",
- "_at",
- "-at",
- "createdat",
- "updatedat",
-];
+// "timestamp" is deliberately absent: any key that contains it already contains "time".
+const DATETIME_PROPERTY_NAME_KEYWORDS: [&str; 6] =
+ ["time", "date", "_at", "-at", "createdat", "updatedat"];
+
+// One automaton pass over the key replaces a `str::contains` per keyword, which
+// paid a two-way searcher setup per call on a per-property hot path.
+static DATETIME_KEYWORD_MATCHER: LazyLock<AhoCorasick> =
+ LazyLock::new(|| AhoCorasick::new(DATETIME_PROPERTY_NAME_KEYWORDS).unwrap());
// TRICKY: the pattern below is a best-effort attempt to classify likely DateTime properties by
// a string prefix of their value. While this doesn't enforce compliance to standard formats,
@@ -330,6 +330,9 @@ impl Event {
group_type: Option<GroupType>,
) {
updates.reserve(set.len() * 2);
+ // The event name repeats in every EventProperty row pushed below, so
+ // sanitize it once instead of once per property.
+ let sanitized_event = sanitize_string(&self.event);
for (key, value) in set {
if SKIP_PROPERTIES.contains(&key.as_str()) && parent_type == PropertyParentType::Event {
continue;
@@ -366,7 +369,7 @@ impl Event {
updates.push(Update::EventProperty(EventProperty {
team_id: self.team_id,
project_id: self.project_id,
- event: sanitize_string(&self.event),
+ event: sanitized_event.clone(),
property: sanitize_string(key),
}));
}
@@ -465,18 +468,13 @@ pub fn detect_property_type(key: &str, value: &Value) -> Option<PropertyValueTyp
}
fn detect_timestamp_property_by_key_and_value(key: &str, value: &Value) -> bool {
- if DATETIME_PROPERTY_NAME_KEYWORDS
- .iter()
- .any(|kw| key.contains(*kw))
- {
- return match value {
- Value::String(s) if is_likely_date_string(s) => true,
- Value::Number(n) if is_likely_unix_timestamp(n) => true,
- _ => false,
- };
+ // Match on the value first: only strings and numbers can classify as
+ // timestamps, so other value types skip the key scan entirely.
+ match value {
+ Value::String(s) => DATETIME_KEYWORD_MATCHER.is_match(key) && is_likely_date_string(s),
+ Value::Number(n) => DATETIME_KEYWORD_MATCHER.is_match(key) && is_likely_unix_timestamp(n),
+ _ => false,
}
-
- false
}
fn is_likely_date_string(s: &str) -> bool {
@@ -610,7 +608,13 @@ fn will_fit_in_postgres_column(str: &str) -> bool {
// This allocates, so only do it right when hitting the DB. We handle nulls
// in strings just fine.
pub fn sanitize_string(s: &str) -> String {
- s.replace('\u{0000}', "\u{FFFD}")
+ // NUL bytes are effectively absent from real traffic, so gate the per-char
+ // replace walk behind a byte scan and take the straight copy otherwise.
+ if s.contains('\u{0000}') {
+ s.replace('\u{0000}', "\u{FFFD}")
+ } else {
+ s.to_owned()
+ }
}
#[cfg(test)]
diff --git a/rust/property-defs-rs/src/update_cache.rs b/rust/property-defs-rs/src/update_cache.rs
index 1a8c04b6ce89..fcefce7fd345 100644
--- a/rust/property-defs-rs/src/update_cache.rs
+++ b/rust/property-defs-rs/src/update_cache.rs
@@ -2,15 +2,21 @@ use crate::{
metrics_consts::{CACHE_EVICTIONS, CACHE_HITS, CACHE_MISSES, UPDATES_CACHE},
types::Update,
};
+use metrics::Counter;
use quick_cache::{sync, DefaultHashBuilder, Lifecycle, UnitWeighter};
// Per-subcache eviction observer. quick_cache's built-in `stats` feature
// only tracks hits/misses on `get`/`get_key_value` paths (not `contains_key`/
// `insert`, which is what we use), so all cache hit/miss/eviction signal in
// this service comes from explicit metrics emitted here and in `contains_key`.
+//
+// Counter handles are resolved once at construction and reused: these paths run
+// per update (and `on_evict` runs under the shard write lock), so a registry
+// lookup per increment is measurable CPU. The metrics recorder must be installed
+// before `Cache::new`, because a handle resolved earlier is a no-op forever.
#[derive(Clone)]
struct EvictingLifecycle {
- cache_label: &'static str,
+ evictions: Counter,
}
impl Lifecycle<Update, ()> for EvictingLifecycle {
@@ -19,26 +25,41 @@ impl Lifecycle<Update, ()> for EvictingLifecycle {
fn begin_request(&self) -> Self::RequestState {}
fn on_evict(&self, _state: &mut Self::RequestState, _key: Update, _val: ()) {
- metrics::counter!(CACHE_EVICTIONS, &[("cache", self.cache_label)]).increment(1);
+ self.evictions.increment(1);
}
}
type SubCache = sync::Cache<Update, (), UnitWeighter, DefaultHashBuilder, EvictingLifecycle>;
-fn build_subcache(capacity: usize, label: &'static str) -> SubCache {
- sync::Cache::with(
+struct SubCacheEntry {
+ cache: SubCache,
+ hits: Counter,
+ misses: Counter,
+}
+
+fn build_subcache(capacity: usize, label: &'static str) -> SubCacheEntry {
+ let cache = sync::Cache::with(
capacity,
capacity as u64,
UnitWeighter,
DefaultHashBuilder::default(),
- EvictingLifecycle { cache_label: label },
- )
+ EvictingLifecycle {
+ evictions: metrics::counter!(CACHE_EVICTIONS, &[("cache", label)]),
+ },
+ );
+ SubCacheEntry {
+ cache,
+ hits: metrics::counter!(CACHE_HITS, &[("cache", label)]),
+ misses: metrics::counter!(CACHE_MISSES, &[("cache", label)]),
+ }
}
pub struct Cache {
- eventdefs: SubCache,
- eventprops: SubCache,
- propdefs: SubCache,
+ eventdefs: SubCacheEntry,
+ eventprops: SubCacheEntry,
+ propdefs: SubCacheEntry,
+ removed: Counter,
+ not_cached: Counter,
}
// TODO: next iter, try using unsync::Cache(s) here and manage sync access to each
@@ -56,55 +77,54 @@ impl Cache {
eventdefs: build_subcache(eventdefs_capacity, "eventdefs"),
eventprops: build_subcache(eventprops_capacity, "eventprops"),
propdefs: build_subcache(propdefs_capacity, "propdefs"),
+ removed: metrics::counter!(UPDATES_CACHE, &[("action", "removed")]),
+ not_cached: metrics::counter!(UPDATES_CACHE, &[("action", "not_cached")]),
+ }
+ }
+
+ fn entry_for(&self, key: &Update) -> &SubCacheEntry {
+ match key {
+ Update::Event(_) => &self.eventdefs,
+ Update::EventProperty(_) => &self.eventprops,
+ Update::Property(_) => &self.propdefs,
}
}
pub fn eventdefs_len(&self) -> usize {
- self.eventdefs.len()
+ self.eventdefs.cache.len()
}
pub fn eventprops_len(&self) -> usize {
- self.eventprops.len()
+ self.eventprops.cache.len()
}
pub fn propdefs_len(&self) -> usize {
- self.propdefs.len()
+ self.propdefs.cache.len()
}
pub fn contains_key(&self, key: &Update) -> bool {
- let (found, label) = match key {
- Update::Event(_) => (self.eventdefs.contains_key(key), "eventdefs"),
- Update::EventProperty(_) => (self.eventprops.contains_key(key), "eventprops"),
- Update::Property(_) => (self.propdefs.contains_key(key), "propdefs"),
- };
+ let entry = self.entry_for(key);
+ let found = entry.cache.contains_key(key);
if found {
- metrics::counter!(CACHE_HITS, &[("cache", label)]).increment(1);
+ entry.hits.increment(1);
} else {
- metrics::counter!(CACHE_MISSES, &[("cache", label)]).increment(1);
+ entry.misses.increment(1);
}
found
}
pub fn insert(&self, key: Update) {
- match key {
- Update::Event(_) => self.eventdefs.insert(key, ()),
- Update::EventProperty(_) => self.eventprops.insert(key, ()),
- Update::Property(_) => self.propdefs.insert(key, ()),
- }
+ self.entry_for(&key).cache.insert(key, ());
}
// we don't return the retrieved KV since propdefs doesn't require it
pub fn remove(&self, key: &Update) {
- let result = match key {
- Update::Event(_) => self.eventdefs.remove(key),
- Update::EventProperty(_) => self.eventprops.remove(key),
- Update::Property(_) => self.propdefs.remove(key),
- };
+ let result = self.entry_for(key).cache.remove(key);
if result.is_some() {
- metrics::counter!(UPDATES_CACHE, &[("action", "removed")]).increment(1);
+ self.removed.increment(1);
} else {
- metrics::counter!(UPDATES_CACHE, &[("action", "not_cached")]).increment(1);
+ self.not_cached.increment(1);
}
}
}
diff --git a/rust/property-defs-rs/tests/update_cache.rs b/rust/property-defs-rs/tests/update_cache.rs
index 040e59e4207a..89aa8fea750f 100644
--- a/rust/property-defs-rs/tests/update_cache.rs
+++ b/rust/property-defs-rs/tests/update_cache.rs
@@ -184,11 +184,14 @@ fn test_uncache_batch_evicts_unresolved_entry_for_group_prop() {
// (post - pre) instead of absolute values because the recorder is shared
// across all tests in the binary and parallel tests touch the same labels.
fn assert_miss_then_hit(label: &'static str, update: Update) {
- let cache = Cache::new(64, 64, 64);
-
+ // Read counters (which installs the recorder) before building the cache:
+ // Cache::new resolves its counter handles once, against whatever recorder
+ // is installed at that moment.
let pre_miss = counter_value(CACHE_MISSES, label);
let pre_hit = counter_value(CACHE_HITS, label);
+ let cache = Cache::new(64, 64, 64);
+
assert!(!cache.contains_key(&update), "fresh cache should miss");
cache.insert(update.clone());
assert!(cache.contains_key(&update), "cached entry should hit");
@@ -223,9 +226,10 @@ fn test_contains_key_emits_hit_miss_metrics(#[case] label: &'static str, #[case]
// subcache. We need >32 distinct inserts to provoke at least one eviction.
#[test]
fn test_overflowing_subcache_emits_eviction_metric() {
- let cache = Cache::new(2, 2, 2);
-
+ // Recorder install must precede Cache::new; see assert_miss_then_hit.
let pre = counter_value(CACHE_EVICTIONS, "eventdefs");
+
+ let cache = Cache::new(2, 2, 2);
for i in 0..200 {
cache.insert(make_event_def(&format!("evict_test_evt_{i}")));
}