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(error-tracking): skip event serialization when no grouping rules (#67218)

Catalin Irimie095e9f54e021
diff --git a/rust/cymbal/src/modes/processing/rules/grouping.rs b/rust/cymbal/src/modes/processing/rules/grouping.rs
index a43c41ac0e69..cdf0947e8a4b 100644
--- a/rust/cymbal/src/modes/processing/rules/grouping.rs
+++ b/rust/cymbal/src/modes/processing/rules/grouping.rs
@@ -3,7 +3,7 @@ use common_types::TeamId;
use hogvm::{ExecutionContext, Program, StepOutcome, VmError};
use serde::Serialize;
use serde_json::Value;
-use sqlx::PgConnection;
+use sqlx::PgPool;
use uuid::Uuid;
use crate::{
@@ -125,20 +125,35 @@ impl GroupingRule {
}
}
-pub async fn evaluate_grouping_rules(
- con: &mut PgConnection,
+pub async fn evaluate_grouping_rules<F>(
+ pool: &PgPool,
team_id: TeamId,
team_manager: &TeamManager,
- props: Value,
-) -> Result<Option<GroupingRule>, UnhandledError> {
+ props: F,
+) -> Result<Option<GroupingRule>, UnhandledError>
+where
+ F: FnOnce() -> Result<Value, UnhandledError>,
+{
let timing = common_metrics::timing_guard(GROUPING_RULES_PROCESSING_TIME, &[]);
- let mut rules = team_manager.get_grouping_rules(&mut *con, team_id).await?;
+ // Pass the pool (not a checked-out connection): `get_grouping_rules` is cache-backed
+ // and only touches the DB on a miss, so nothing holds a connection across the cache
+ // lookup, `props()` serialization, or HogVM rule evaluation below.
+ let mut rules = team_manager.get_grouping_rules(pool, team_id).await?;
metrics::counter!(GROUPING_RULES_FOUND).increment(rules.len() as u64);
+ // Most teams have no grouping rules. Bail before materializing `props`, which
+ // the caller defers (serializing the event to JSON is expensive per-event work).
+ if rules.is_empty() {
+ timing.label("outcome", "no_match").fin();
+ return Ok(None);
+ }
+
rules.sort_unstable_by_key(|r| r.order_key);
+ let props = props()?;
+
for rule in rules {
match rule.try_match(&props) {
Ok(false) => continue,
@@ -159,10 +174,7 @@ pub async fn evaluate_grouping_rules(
);
continue;
}
- Err(err) => {
- rule.disable(&mut *con, err.to_string(), props.clone())
- .await?
- }
+ Err(err) => rule.disable(pool, err.to_string(), props.clone()).await?,
}
}
@@ -223,7 +235,6 @@ mod test {
#[sqlx::test(migrations = "./tests/test_migrations")]
async fn test_grouping_rules(db: PgPool) {
let ctx = create_test_context(db).await;
- let mut conn = ctx.posthog_pool.acquire().await.unwrap();
let test_team_id = 1;
let props = test_props(JsonValue::from("test_value"));
@@ -236,9 +247,11 @@ mod test {
.insert(test_team_id, vec![rule]);
let matched =
- evaluate_grouping_rules(&mut conn, test_team_id, &ctx.team_manager, props.clone())
- .await
- .unwrap();
+ evaluate_grouping_rules(&ctx.posthog_pool, test_team_id, &ctx.team_manager, || {
+ Ok(props.clone())
+ })
+ .await
+ .unwrap();
let fingerprint = Fingerprint::from_rule(matched.expect("rule should match"));
assert_eq!(fingerprint.value, expected_fingerprint);
@@ -247,7 +260,10 @@ mod test {
// tries to access an undefined global
let props = test_props(JsonValue::from("no_match"));
- let matched = evaluate_grouping_rules(&mut conn, test_team_id, &ctx.team_manager, props)
+ let matched =
+ evaluate_grouping_rules(&ctx.posthog_pool, test_team_id, &ctx.team_manager, || {
+ Ok(props)
+ })
.await
.unwrap();
diff --git a/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs b/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs
index 8b8111759b77..1e8d02f5a2df 100644
--- a/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs
+++ b/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs
@@ -30,12 +30,14 @@ impl ValueOperator for FingerprintGenerator {
mut input: ExceptionProperties,
ctx: GroupingStage,
) -> OperatorResult<Self> {
- // Generate fingerprint (uses resolved frames for hashing, or applies grouping rules)
- let props = serde_json::to_value(&input)?;
- let mut conn = ctx.connection.acquire().await?;
+ // Generate fingerprint (uses resolved frames for hashing, or applies grouping rules).
+ // Serializing the event to JSON is only needed when the team has grouping rules, so
+ // defer it: `evaluate_grouping_rules` invokes this closure only when rules exist.
let fingerprint: Fingerprint =
- match evaluate_grouping_rules(&mut conn, input.team_id, &ctx.team_manager, props)
- .await?
+ match evaluate_grouping_rules(&ctx.connection, input.team_id, &ctx.team_manager, || {
+ Ok(serde_json::to_value(&input)?)
+ })
+ .await?
{
Some(rule) => Fingerprint::from_rule(rule),
None => Fingerprint::from_exception_list(&input.exception_list),