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(personhog): time the leader's release-fence phases and fallback pool waits (#98926)

Nick Best2d6f9748fa1e
diff --git a/rust/personhog-leader/src/fence.rs b/rust/personhog-leader/src/fence.rs
index 5384f87fc612..896c239a679d 100644
--- a/rust/personhog-leader/src/fence.rs
+++ b/rust/personhog-leader/src/fence.rs
@@ -323,6 +323,7 @@ pub async fn mark_status(
team_id: i64,
person_id: i64,
) -> Result<Option<String>, sqlx::Error> {
+ let mut conn = crate::pg::acquire_timed(pool, "mark_status").await?;
sqlx::query_scalar(
"SELECT status FROM lifecycle_op_person \
WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role <> 'target'",
@@ -330,7 +331,7 @@ pub async fn mark_status(
.bind(op_id)
.bind(team_id as i32)
.bind(person_id)
- .fetch_optional(pool)
+ .fetch_optional(&mut *conn)
.await
}
@@ -349,6 +350,7 @@ pub async fn target_mark_status(
team_id: i64,
person_id: i64,
) -> Result<Option<String>, sqlx::Error> {
+ let mut conn = crate::pg::acquire_timed(pool, "target_mark_status").await?;
sqlx::query_scalar(
"SELECT status FROM lifecycle_op_person \
WHERE op_id = $1 AND team_id = $2 AND person_id = $3 AND role = 'target'",
@@ -356,6 +358,6 @@ pub async fn target_mark_status(
.bind(op_id)
.bind(team_id as i32)
.bind(person_id)
- .fetch_optional(pool)
+ .fetch_optional(&mut *conn)
.await
}
diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rs
index ff1ad5d45eac..9d25e72a3351 100644
--- a/rust/personhog-leader/src/main.rs
+++ b/rust/personhog-leader/src/main.rs
@@ -200,6 +200,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Matcher::Full("personhog_leader_person_lock_wait_ms".into()),
WRITE_PATH_LATENCY_BUCKETS_MS,
),
+ (
+ Matcher::Full("personhog_leader_release_phase_ms".into()),
+ WRITE_PATH_LATENCY_BUCKETS_MS,
+ ),
+ (
+ Matcher::Full("personhog_leader_fallback_pool_acquire_ms".into()),
+ WRITE_PATH_LATENCY_BUCKETS_MS,
+ ),
(
Matcher::Full("grpc_server_request_duration_ms".into()),
WRITE_PATH_LATENCY_BUCKETS_MS,
@@ -296,13 +304,22 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
statement_timeout_ms: Some(5_000),
..Default::default()
};
- Some(PgFallback {
+ let fallback = PgFallback {
pool: common_database::get_pool_with_config(
&config.fallback_database_url,
pool_config,
)?,
table: config.fallback_table.clone(),
- })
+ };
+ personhog_common::spawn_pool_monitor(
+ vec![personhog_common::MonitoredPool {
+ pool: fallback.pool.clone(),
+ label: "fallback".to_string(),
+ max_connections: config.fallback_pg_max_connections,
+ }],
+ Duration::from_secs(10),
+ );
+ Some(fallback)
};
// Connect to etcd for coordination and the partition count
diff --git a/rust/personhog-leader/src/pg.rs b/rust/personhog-leader/src/pg.rs
index fbe319d12801..716751fb00d2 100644
--- a/rust/personhog-leader/src/pg.rs
+++ b/rust/personhog-leader/src/pg.rs
@@ -1,7 +1,10 @@
+use std::time::Instant;
+
use metrics::{counter, histogram};
use personhog_common::properties::rewrite_out_of_range_numbers;
+use sqlx::pool::PoolConnection;
use sqlx::postgres::PgPool;
-use sqlx::Row;
+use sqlx::{Postgres, Row};
use crate::cache::{approx_person_bytes, CachedPerson, PersonCacheKey};
@@ -15,6 +18,19 @@ pub struct PgFallback {
pub table: String,
}
+/// Take a fallback-pool connection, recording the wait: the pool is small
+/// and shared by cache-miss loads and the sagas' mark checks.
+pub async fn acquire_timed(
+ pool: &PgPool,
+ caller: &'static str,
+) -> Result<PoolConnection<Postgres>, sqlx::Error> {
+ let start = Instant::now();
+ let conn = pool.acquire().await;
+ histogram!("personhog_leader_fallback_pool_acquire_ms", "caller" => caller)
+ .record(start.elapsed().as_secs_f64() * 1000.0);
+ conn
+}
+
/// Validate a configured table identifier before it is interpolated into
/// SQL (identifiers cannot be bound as parameters).
pub fn validate_table_name(table: &str) -> Result<(), String> {
@@ -32,7 +48,8 @@ pub async fn load_person_from_pg(
table: &str,
key: &PersonCacheKey,
) -> Result<Option<CachedPerson>, sqlx::Error> {
- let start = std::time::Instant::now();
+ let start = Instant::now();
+ let mut conn = acquire_timed(pool, "load_person").await?;
let team_id_i32 = i32::try_from(key.team_id)
.map_err(|_| sqlx::Error::Protocol(format!("team_id {} exceeds i32 range", key.team_id)))?;
@@ -52,8 +69,10 @@ pub async fn load_person_from_pg(
))
.bind(team_id_i32)
.bind(key.person_id)
- .fetch_optional(pool)
+ .fetch_optional(&mut *conn)
.await?;
+ // The row is owned; parsing its properties must not hold the pool slot.
+ drop(conn);
histogram!("personhog_leader_pg_fallback_duration_ms")
.record(start.elapsed().as_secs_f64() * 1000.0);
diff --git a/rust/personhog-leader/src/service.rs b/rust/personhog-leader/src/service.rs
index e71f0d69e8c8..f805e21242e7 100644
--- a/rust/personhog-leader/src/service.rs
+++ b/rust/personhog-leader/src/service.rs
@@ -887,6 +887,13 @@ fn partition_from_metadata<T>(request: &Request<T>) -> Result<u32, Status> {
.map_err(|_| Status::invalid_argument("x-partition metadata is not a valid u32"))
}
+/// Per-phase wall time of a committed release; the RPC histogram alone
+/// cannot separate the lock, the load, the mark check, and the produce.
+fn record_release_phase(phase: &'static str, started: Instant) {
+ histogram!("personhog_leader_release_phase_ms", "phase" => phase)
+ .record(started.elapsed().as_secs_f64() * 1000.0);
+}
+
#[tonic::async_trait]
impl PersonHogLeader for PersonHogLeaderService {
async fn get_person(
@@ -1749,6 +1756,7 @@ impl PersonHogLeader for PersonHogLeaderService {
.or_default()
.value()
.clone();
+ let lock_started = Instant::now();
let _guard = mutex.lock().await;
// Releasing another op's fence would break that op's seal.
@@ -1760,6 +1768,7 @@ impl PersonHogLeader for PersonHogLeaderService {
match outcome {
ReleaseOutcome::Committed => {
+ record_release_phase("lock_wait", lock_started);
// 0 is a legitimate sealed version (a fresh stub's),
// which is why the field is explicitly optional in the proto.
let Some(sealed_version) = req.sealed_version else {
@@ -1793,7 +1802,10 @@ impl PersonHogLeader for PersonHogLeaderService {
// Release must stay idempotent for the saga's retry and the
// sweeper, so a person the leader cannot load anymore is
// tolerated.
- let current = match self.lookup_or_load_locked(partition, &cache_key).await {
+ let load_started = Instant::now();
+ let loaded = self.lookup_or_load_locked(partition, &cache_key).await;
+ record_release_phase("load", load_started);
+ let current = match loaded {
Ok(person) => Some(person),
Err(status) if status.code() == tonic::Code::NotFound => None,
Err(status) => return Err(status),
@@ -1835,7 +1847,10 @@ impl PersonHogLeader for PersonHogLeaderService {
"no-lifecycle-db",
));
};
- match mark_status(&fallback.pool, op_id, req.team_id, req.person_id).await {
+ let verify_started = Instant::now();
+ let mark = mark_status(&fallback.pool, op_id, req.team_id, req.person_id).await;
+ record_release_phase("verify_mark", verify_started);
+ match mark {
// A live mark: the op holds the person; proceed.
Ok(Some(status)) if status == "marked" || status == "sealed" => {}
// The mark already settled as deleted: this release
@@ -1907,7 +1922,10 @@ impl PersonHogLeader for PersonHogLeaderService {
last_seen_at: None,
approx_bytes: approx_person_bytes(2),
};
- self.commit_document(partition, &cache_key, death).await?;
+ let produce_started = Instant::now();
+ let committed = self.commit_document(partition, &cache_key, death).await;
+ record_release_phase("produce", produce_started);
+ committed?;
// The death document stays cached while its mark stands,
// answering an authoritative not-found from memory; the
// prune-time settle drops it once the writer confirms,