: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(personhog): isolate bulk queries into dedicated connection pools (#58209)
Nick Besta0c01a55109a
diff --git a/rust/personhog-replica/src/config.rs b/rust/personhog-replica/src/config.rsindex 8a1e73105f35..c24f6c895820 100644--- a/rust/personhog-replica/src/config.rs+++ b/rust/personhog-replica/src/config.rs@@ -35,6 +35,20 @@ pub struct Config {#[envconfig(default = "5000")]pub statement_timeout_ms: u64,+ /// Max connections for the bulk pool (large batch reads, deletes).+ /// Kept small so bulk queries can't starve the fast pool.+ #[envconfig(default = "5")]+ pub bulk_max_pg_connections: u32,++ /// Statement timeout for bulk queries (ms). Longer than the fast pool+ /// because batch reads over thousands of IDs legitimately take seconds.+ #[envconfig(default = "30000")]+ pub bulk_statement_timeout_ms: u64,++ /// Acquire timeout for bulk pool (seconds).+ #[envconfig(default = "10")]+ pub bulk_acquire_timeout_secs: u64,+/// Maximum number of server-side (PgBouncer → Postgres) connections to/// warm at startup via SELECT 1. Clamped to min_pg_connections. Set to 0/// to skip server-side warming entirely.@@ -75,6 +89,18 @@ impl Config {Duration::from_secs(self.acquire_timeout_secs)}+ pub fn bulk_acquire_timeout(&self) -> Duration {+ Duration::from_secs(self.bulk_acquire_timeout_secs)+ }++ pub fn bulk_statement_timeout(&self) -> Option<u64> {+ if self.bulk_statement_timeout_ms == 0 {+ None+ } else {+ Some(self.bulk_statement_timeout_ms)+ }+ }+pub fn idle_timeout(&self) -> Option<Duration> {if self.idle_timeout_secs == 0 {Nonediff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rsindex 7b03cd5ce189..4cc7b6c83a67 100644--- a/rust/personhog-replica/src/main.rs+++ b/rust/personhog-replica/src/main.rs@@ -41,6 +41,22 @@ async fn create_storage(config: &Config) -> Arc<PostgresStorage> {..primary_pool_config.clone()};+ let bulk_primary_pool_config = PoolConfig {+ min_connections: config+ .min_pg_connections+ .min(config.bulk_max_pg_connections),+ max_connections: config.bulk_max_pg_connections,+ acquire_timeout: config.bulk_acquire_timeout(),+ statement_timeout_ms: config.bulk_statement_timeout(),+ pool_name: Some("bulk_primary".to_string()),+ ..primary_pool_config.clone()+ };++ let bulk_replica_pool_config = PoolConfig {+ pool_name: Some("bulk_replica".to_string()),+ ..bulk_primary_pool_config.clone()+ };+// Create primary poollet primary_pool =get_pool_with_config(&config.primary_database_url, primary_pool_config)@@ -59,7 +75,29 @@ async fn create_storage(config: &Config) -> Arc<PostgresStorage> {pool};- Arc::new(PostgresStorage::new(primary_pool, replica_pool))+ // Create bulk pools (same URLs, smaller pool with longer timeouts)+ let bulk_primary_pool =+ get_pool_with_config(&config.primary_database_url, bulk_primary_pool_config)+ .expect("Failed to create bulk primary database pool");++ let bulk_replica_pool = if replica_url == config.primary_database_url {+ bulk_primary_pool.clone()+ } else {+ get_pool_with_config(replica_url, bulk_replica_pool_config)+ .expect("Failed to create bulk replica database pool")+ };+ tracing::info!(+ max_connections = config.bulk_max_pg_connections,+ statement_timeout_ms = config.bulk_statement_timeout_ms,+ "Created bulk database pools"+ );++ Arc::new(PostgresStorage::new(+ primary_pool,+ replica_pool,+ bulk_primary_pool,+ bulk_replica_pool,+ ))}other => {panic!("Unknown storage backend: {other}. Supported: postgres");@@ -229,6 +267,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {label: "replica".to_string(),max_connections: config.max_pg_connections,});+ pools.push(MonitoredPool {+ pool: storage.bulk_primary_pool.clone(),+ label: "bulk_primary".to_string(),+ max_connections: config.bulk_max_pg_connections,+ });+ pools.push(MonitoredPool {+ pool: storage.bulk_replica_pool.clone(),+ label: "bulk_replica".to_string(),+ max_connections: config.bulk_max_pg_connections,+ });spawn_pool_monitor(pools,Duration::from_secs(config.pool_monitor_interval_secs),diff --git a/rust/personhog-replica/src/storage/postgres/cohort.rs b/rust/personhog-replica/src/storage/postgres/cohort.rsindex 062ba42da0b9..225ce08796f3 100644--- a/rust/personhog-replica/src/storage/postgres/cohort.rs+++ b/rust/personhog-replica/src/storage/postgres/cohort.rs@@ -150,12 +150,13 @@ impl CohortStorage for PostgresStorage {"operation".to_string(),"delete_cohort_members_bulk".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_primary_pool, "bulk_primary").await?;let cohort_ids_i32: Vec<i32> = cohort_ids.iter().map(|&id| id as i32).collect();diff --git a/rust/personhog-replica/src/storage/postgres/distinct_id.rs b/rust/personhog-replica/src/storage/postgres/distinct_id.rsindex 653630811c18..5b2eb468d4e3 100644--- a/rust/personhog-replica/src/storage/postgres/distinct_id.rs+++ b/rust/personhog-replica/src/storage/postgres/distinct_id.rs@@ -91,7 +91,7 @@ impl DistinctIdLookup for PostgresStorage {}let client = current_client_name();- let pool_label = PostgresStorage::pool_label(consistency);+ let pool_label = PostgresStorage::bulk_pool_label(consistency);let labels = [("operation".to_string(),@@ -102,7 +102,7 @@ impl DistinctIdLookup for PostgresStorage {];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let pool = self.pool_for_consistency(consistency);+ let pool = self.bulk_pool_for_consistency(consistency);let mut conn = PostgresStorage::acquire_timed(pool, pool_label).await?;let rows = match limit_per_person {diff --git a/rust/personhog-replica/src/storage/postgres/group.rs b/rust/personhog-replica/src/storage/postgres/group.rsindex 4af0735159fb..d3dcd15c356f 100644--- a/rust/personhog-replica/src/storage/postgres/group.rs+++ b/rust/personhog-replica/src/storage/postgres/group.rs@@ -643,12 +643,13 @@ impl GroupStorage for PostgresStorage {"operation".to_string(),"delete_groups_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_primary_pool, "bulk_primary").await?;let result = sqlx::query!(r#"@@ -673,7 +674,7 @@ impl GroupStorage for PostgresStorage {"operation".to_string(),"delete_groups_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),],result.rows_affected() as f64,@@ -811,12 +812,13 @@ impl GroupStorage for PostgresStorage {"operation".to_string(),"delete_group_type_mappings_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_primary_pool, "bulk_primary").await?;let result = sqlx::query!(r#"@@ -841,7 +843,7 @@ impl GroupStorage for PostgresStorage {"operation".to_string(),"delete_group_type_mappings_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),],result.rows_affected() as f64,diff --git a/rust/personhog-replica/src/storage/postgres/mod.rs b/rust/personhog-replica/src/storage/postgres/mod.rsindex 404954c32ef3..6c3a82e8e807 100644--- a/rust/personhog-replica/src/storage/postgres/mod.rs+++ b/rust/personhog-replica/src/storage/postgres/mod.rs@@ -27,29 +27,42 @@ pub enum ConsistencyLevel {}/// Postgres implementation of storage traits with dual-pool support-/// for primary (strong consistency) and replica (eventual consistency) databases.+/// for primary (strong consistency) and replica (eventual consistency) databases,+/// plus dedicated bulk pools for heavy batch operations.pub struct PostgresStorage {/// Connection pool for the primary database (writes + strong consistency reads)pub primary_pool: PgPool,/// Connection pool for the replica database (eventual consistency reads)pub replica_pool: PgPool,+ /// Bulk pool for the primary database (heavy deletes, batch writes)+ pub bulk_primary_pool: PgPool,+ /// Bulk pool for the replica database (large batch reads)+ pub bulk_replica_pool: PgPool,}impl PostgresStorage {- /// Create a new PostgresStorage with separate primary and replica pools.- /// For single-database setups, pass the same pool for both.- pub fn new(primary_pool: PgPool, replica_pool: PgPool) -> Self {+ /// Create a new PostgresStorage with separate primary, replica, and bulk pools.+ pub fn new(+ primary_pool: PgPool,+ replica_pool: PgPool,+ bulk_primary_pool: PgPool,+ bulk_replica_pool: PgPool,+ ) -> Self {Self {primary_pool,replica_pool,+ bulk_primary_pool,+ bulk_replica_pool,}}- /// Create a new PostgresStorage with a single pool used for both primary and replica.+ /// Create a new PostgresStorage with a single pool used for everything.pub fn new_single_pool(pool: PgPool) -> Self {Self {primary_pool: pool.clone(),- replica_pool: pool,+ replica_pool: pool.clone(),+ bulk_primary_pool: pool.clone(),+ bulk_replica_pool: pool,}}@@ -63,6 +76,21 @@ impl PostgresStorage {}}+ /// Get the appropriate bulk pool based on consistency level.+ pub(crate) fn bulk_pool_for_consistency(&self, consistency: ConsistencyLevel) -> &PgPool {+ match consistency {+ ConsistencyLevel::Strong => &self.bulk_primary_pool,+ ConsistencyLevel::Eventual => &self.bulk_replica_pool,+ }+ }++ pub(crate) fn bulk_pool_label(consistency: ConsistencyLevel) -> &'static str {+ match consistency {+ ConsistencyLevel::Strong => "bulk_primary",+ ConsistencyLevel::Eventual => "bulk_replica",+ }+ }+/// Returns the pool label for the given consistency level.pub(crate) fn pool_label(consistency: ConsistencyLevel) -> &'static str {match consistency {diff --git a/rust/personhog-replica/src/storage/postgres/person.rs b/rust/personhog-replica/src/storage/postgres/person.rsindex 9c98966af955..4b63cdaecced 100644--- a/rust/personhog-replica/src/storage/postgres/person.rs+++ b/rust/personhog-replica/src/storage/postgres/person.rs@@ -11,6 +11,7 @@ use crate::storage::traits::PersonLookup;use crate::storage::types::Person;const POOL_LABEL: &str = "replica";+const BULK_POOL_LABEL: &str = "bulk_replica";#[async_trait]impl PersonLookup for PostgresStorage {@@ -92,12 +93,13 @@ impl PersonLookup for PostgresStorage {let client = current_client_name();let labels = [("operation".to_string(), "get_persons_by_ids".to_string()),- ("pool".to_string(), POOL_LABEL.to_string()),+ ("pool".to_string(), BULK_POOL_LABEL.to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.replica_pool, POOL_LABEL).await?;+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;let rows = sqlx::query_as!(Person,@@ -140,12 +142,13 @@ impl PersonLookup for PostgresStorage {let client = current_client_name();let labels = [("operation".to_string(), "get_persons_by_uuids".to_string()),- ("pool".to_string(), POOL_LABEL.to_string()),+ ("pool".to_string(), BULK_POOL_LABEL.to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.replica_pool, POOL_LABEL).await?;+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;let rows = sqlx::query_as!(Person,@@ -231,14 +234,13 @@ impl PersonLookup for PostgresStorage {"operation".to_string(),"get_persons_by_distinct_ids_in_team".to_string(),),- ("pool".to_string(), POOL_LABEL.to_string()),+ ("pool".to_string(), BULK_POOL_LABEL.to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.replica_pool, POOL_LABEL).await?;-- // Use query!() since we need distinct_id alongside Person fields+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;let rows = sqlx::query!(r#"SELECT p.id, p.uuid as "uuid!", p.team_id::bigint as "team_id!",@@ -304,12 +306,12 @@ impl PersonLookup for PostgresStorage {let client = current_client_name();let labels = [("operation".to_string(), "delete_persons".to_string()),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut tx = self.primary_pool.begin().await?;+ let mut tx = self.bulk_primary_pool.begin().await?;// Delete distinct_id rows first — the FK on posthog_persondistinctid.person_id// is NO ACTION, so the person delete would fail if these still exist.@@ -332,7 +334,7 @@ impl PersonLookup for PostgresStorage {"operation".to_string(),"delete_distinct_ids_for_persons".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),],did_result.rows_affected() as f64,@@ -355,7 +357,7 @@ impl PersonLookup for PostgresStorage {DB_ROWS_RETURNED,&[("operation".to_string(), "delete_persons".to_string()),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),],result.rows_affected() as f64,@@ -381,12 +383,12 @@ impl PersonLookup for PostgresStorage {"operation".to_string(),"delete_persons_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut tx = self.primary_pool.begin().await?;+ let mut tx = self.bulk_primary_pool.begin().await?;// Step 1: Select up to batch_size person IDs for the teamlet person_ids: Vec<i64> = sqlx::query_scalar!(@@ -426,7 +428,7 @@ impl PersonLookup for PostgresStorage {"operation".to_string(),"delete_distinct_ids_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),],did_result.rows_affected() as f64,@@ -451,7 +453,7 @@ impl PersonLookup for PostgresStorage {"operation".to_string(),"delete_persons_batch_for_team".to_string(),),- ("pool".to_string(), "primary".to_string()),+ ("pool".to_string(), "bulk_primary".to_string()),("client".to_string(), client.to_string()),],result.rows_affected() as f64,@@ -476,12 +478,13 @@ impl PersonLookup for PostgresStorage {"operation".to_string(),"get_persons_by_distinct_ids_cross_team".to_string(),),- ("pool".to_string(), POOL_LABEL.to_string()),+ ("pool".to_string(), BULK_POOL_LABEL.to_string()),("client".to_string(), client.to_string()),];let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);- let mut conn = PostgresStorage::acquire_timed(&self.replica_pool, POOL_LABEL).await?;+ let mut conn =+ PostgresStorage::acquire_timed(&self.bulk_replica_pool, BULK_POOL_LABEL).await?;let team_ids: Vec<i32> = team_distinct_ids.iter().map(|(t, _)| *t as i32).collect();let distinct_ids: Vec<String> = team_distinct_ids.iter().map(|(_, d)| d.clone()).collect();diff --git a/rust/personhog-replica/tests/common/mod.rs b/rust/personhog-replica/tests/common/mod.rsindex 1da22b47f08c..c6b90947f8e0 100644--- a/rust/personhog-replica/tests/common/mod.rs+++ b/rust/personhog-replica/tests/common/mod.rs@@ -28,8 +28,8 @@ impl TestContext {let pool = PgPool::connect(&database_url).await.expect("Failed to connect to test database");- // In tests, use the same pool for both primary and replica- let storage = Arc::new(PostgresStorage::new(pool.clone(), pool.clone()));+ // In tests, use the same pool for everything+ let storage = Arc::new(PostgresStorage::new_single_pool(pool.clone()));let team_id = random_team_id();Self {