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): split identity's Postgres pool into fast and heavy lanes (#98929)

Nick Besta0ea7f0a2d2c
diff --git a/rust/personhog-identity/README.md b/rust/personhog-identity/README.md
index 38eb0d33b7fe..1462af27cda2 100644
--- a/rust/personhog-identity/README.md
+++ b/rust/personhog-identity/README.md
@@ -20,7 +20,8 @@ Races resolve per key, never failing the rest of a batch: a concurrent create co
## Layout
- `src/service/` — gRPC surface; `mod.rs` is dispatch-only, each RPC family has its own module (`get_or_create.rs`)
-- `src/storage/` — `IdentityStorage` trait + Postgres implementation (primary pool only; identity reads must never be stale)
+- `src/storage/` — `IdentityStorage` trait + Postgres implementation (primary only; identity reads must never be stale)
+- `src/pools.rs` — the two primary pools, split by how long a statement holds its connection: fast (resolution, op bookkeeping) and heavy (stub creation, attach, saga transactions, GC), sized by `MAX_PG_CONNECTIONS` and `HEAVY_MAX_PG_CONNECTIONS`
- `src/leader.rs` — `PropertyWriter` trait + router-backed implementation
- `src/lifecycle/` — the lifecycle engine: merge and delete sagas, sweeper, GC
- Shared person primitives (row type, storage errors, uuidv5 scheme) live in `personhog-common::persons`
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index 29a53efc550c..be476c62c42d 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -1,7 +1,10 @@
+use common_database::PoolConfig;
use envconfig::Envconfig;
use std::net::SocketAddr;
use std::time::Duration;
+use crate::pools::Lane;
+
#[derive(Envconfig, Clone, Debug)]
pub struct Config {
#[envconfig(default = "127.0.0.1:50055")]
@@ -43,6 +46,7 @@ pub struct Config {
#[envconfig(default = "lifecycle_op_person_tmp")]
pub lifecycle_op_person_table: String,
+ /// Fast pool (see `crate::pools`).
#[envconfig(default = "10")]
pub max_pg_connections: u32,
@@ -52,12 +56,27 @@ pub struct Config {
#[envconfig(default = "10")]
pub acquire_timeout_secs: u64,
- #[envconfig(default = "300")]
- pub idle_timeout_secs: u64,
-
#[envconfig(default = "5000")]
pub statement_timeout_ms: u64,
+ /// Heavy pool, sized separately so a burst of long transactions cannot
+ /// take the fast pool's slots.
+ #[envconfig(default = "10")]
+ pub heavy_max_pg_connections: u32,
+
+ #[envconfig(default = "0")]
+ pub heavy_min_pg_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub heavy_acquire_timeout_secs: u64,
+
+ #[envconfig(default = "5000")]
+ pub heavy_statement_timeout_ms: u64,
+
+ /// Applies to both pools.
+ #[envconfig(default = "300")]
+ pub idle_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.
@@ -259,10 +278,6 @@ impl Config {
}
}
- pub fn acquire_timeout(&self) -> Duration {
- Duration::from_secs(self.acquire_timeout_secs)
- }
-
pub fn idle_timeout(&self) -> Option<Duration> {
if self.idle_timeout_secs == 0 {
None
@@ -271,11 +286,42 @@ impl Config {
}
}
- pub fn statement_timeout(&self) -> Option<u64> {
- if self.statement_timeout_ms == 0 {
- None
- } else {
- Some(self.statement_timeout_ms)
+ pub fn fast_pool_config(&self) -> PoolConfig {
+ self.pool_config(
+ Lane::Fast,
+ self.min_pg_connections,
+ self.max_pg_connections,
+ self.acquire_timeout_secs,
+ self.statement_timeout_ms,
+ )
+ }
+
+ pub fn heavy_pool_config(&self) -> PoolConfig {
+ self.pool_config(
+ Lane::Heavy,
+ self.heavy_min_pg_connections,
+ self.heavy_max_pg_connections,
+ self.heavy_acquire_timeout_secs,
+ self.heavy_statement_timeout_ms,
+ )
+ }
+
+ fn pool_config(
+ &self,
+ lane: Lane,
+ min_connections: u32,
+ max_connections: u32,
+ acquire_timeout_secs: u64,
+ statement_timeout_ms: u64,
+ ) -> PoolConfig {
+ PoolConfig {
+ min_connections,
+ max_connections,
+ acquire_timeout: Duration::from_secs(acquire_timeout_secs),
+ idle_timeout: self.idle_timeout(),
+ test_before_acquire: false,
+ statement_timeout_ms: (statement_timeout_ms != 0).then_some(statement_timeout_ms),
+ pool_name: Some(lane.label().to_string()),
}
}
diff --git a/rust/personhog-identity/src/lib.rs b/rust/personhog-identity/src/lib.rs
index a3690b4e791e..30a9c9601098 100644
--- a/rust/personhog-identity/src/lib.rs
+++ b/rust/personhog-identity/src/lib.rs
@@ -1,5 +1,6 @@
pub mod config;
pub mod leader;
pub mod lifecycle;
+pub mod pools;
pub mod service;
pub mod storage;
diff --git a/rust/personhog-identity/src/lifecycle/delete.rs b/rust/personhog-identity/src/lifecycle/delete.rs
index b880e5d1aa8f..193de97bb49b 100644
--- a/rust/personhog-identity/src/lifecycle/delete.rs
+++ b/rust/personhog-identity/src/lifecycle/delete.rs
@@ -26,7 +26,6 @@ use async_trait::async_trait;
use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use sqlx::postgres::PgPool;
use uuid::Uuid;
use personhog_proto::personhog::types::v1::LifecycleOpType;
@@ -40,7 +39,7 @@ use crate::lifecycle::engine::{
use crate::lifecycle::leader_calls::{
fence_victims, release_fenced, Fenced, FencedVictim, LeaderCalls,
};
-use crate::storage::postgres::begin_timed;
+use crate::pools::{IdentityPools, Lane};
// Derived from the shared enum so the op-type string cannot drift from
// the leader's fence records or the lifecycle_op CHECK constraint.
@@ -192,7 +191,7 @@ impl OpDriver for DeleteDriver {
DeleteStep::Started.as_str()
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
let step = DeleteStep::parse(&op.step).ok_or_else(|| {
SagaError::CorruptState(format!(
"delete op {} is on unknown step '{}'",
@@ -200,10 +199,10 @@ impl OpDriver for DeleteDriver {
))
})?;
match step {
- DeleteStep::Started => mark(pool, &self.tables, op).await,
- DeleteStep::Marked => seal(pool, self.leader_calls(), &self.tables, op).await,
- DeleteStep::Sealed => unmap(pool, &self.tables, op).await,
- DeleteStep::Unmapped => complete(pool, self.leader_calls(), &self.tables, op).await,
+ DeleteStep::Started => mark(pools, &self.tables, op).await,
+ DeleteStep::Marked => seal(pools, self.leader_calls(), &self.tables, op).await,
+ DeleteStep::Sealed => unmap(pools, &self.tables, op).await,
+ DeleteStep::Unmapped => complete(pools, self.leader_calls(), &self.tables, op).await,
}
}
}
@@ -223,11 +222,11 @@ fn parse_request(op: &OpRow) -> Result<DeleteRequest, SagaError> {
/// `skipped_conflict`. Requested ids with no live person row get no row at
/// all — they surface as `not_found` in the outcome. If nothing was claimed
/// the op aborts here, before anything was mutated.
-async fn mark(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
+async fn mark(pools: &IdentityPools, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
let team_id = op.team_id as i32;
let person_table = &tables.person;
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
// Rows from a previous attempt of this op (crash between the insert and
// the advance): whatever they claimed stays claimed.
@@ -403,7 +402,7 @@ async fn mark(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
/// past `started`, and a parked delete is an operator signal, not a stuck
/// customer flow.
async fn seal(
- pool: &PgPool,
+ pools: &IdentityPools,
calls: LeaderCalls<'_>,
tables: &IdentityTables,
op: &OpRow,
@@ -416,7 +415,7 @@ async fn seal(
ORDER BY person_id
"#,
op.op_id
- => fetch_all(pool)
+ => fetch_all(pools.fast())
)?;
let fenced = fence_victims(calls, op, &victims).await?;
@@ -446,7 +445,7 @@ async fn seal(
}
}
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
mirrored_query!(
tables.is_validation(),
r#"
@@ -501,9 +500,13 @@ async fn seal(
/// at sealed + 1 so the tombstone outranks every write the old incarnation
/// ever produced. Revival (a later create on the same key) upserts above
/// this version.
-async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
+async fn unmap(
+ pools: &IdentityPools,
+ tables: &IdentityTables,
+ op: &OpRow,
+) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
let mut victims: Vec<i64> = mirrored_query_scalar!(
tables.is_validation(),
@@ -664,7 +667,7 @@ async fn unmap(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(),
/// exactly when `FencePerson` sealed them, so an op sealed pre-fence (or
/// across a kill-switch flip) completes without phantom release calls.
async fn complete(
- pool: &PgPool,
+ pools: &IdentityPools,
calls: LeaderCalls<'_>,
tables: &IdentityTables,
op: &OpRow,
@@ -683,11 +686,11 @@ async fn complete(
ORDER BY person_id
"#,
op.op_id
- => fetch_all(pool)
+ => fetch_all(pools.fast())
)?;
release_fenced(calls, op, &fenced).await?;
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
mirrored_query!(
tables.is_validation(),
diff --git a/rust/personhog-identity/src/lifecycle/engine.rs b/rust/personhog-identity/src/lifecycle/engine.rs
index d7f3e9330b7e..c9722b5a0555 100644
--- a/rust/personhog-identity/src/lifecycle/engine.rs
+++ b/rust/personhog-identity/src/lifecycle/engine.rs
@@ -23,11 +23,11 @@ use chrono::{DateTime, Utc};
use common_sqlx_macros::{mirrored_query, mirrored_query_as, mirrored_query_scalar};
use rand::Rng;
use serde_json::Value;
-use sqlx::postgres::PgPool;
use tonic::Status;
use uuid::Uuid;
use crate::config::IdentityTables;
+use crate::pools::{IdentityPools, Lane};
/// Terminal step: the op ran to the end.
pub const STEP_COMPLETED: &str = "completed";
@@ -191,7 +191,7 @@ pub trait OpDriver: Send + Sync {
fn op_type(&self) -> &'static str;
/// The step a freshly created op row starts on.
fn initial_step(&self) -> &'static str;
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError>;
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError>;
}
#[derive(Clone, Debug)]
@@ -211,23 +211,23 @@ pub struct EngineConfig {
}
pub struct Engine {
- pool: PgPool,
+ pools: IdentityPools,
config: EngineConfig,
tables: IdentityTables,
}
impl Engine {
- pub fn new(pool: PgPool, config: EngineConfig, tables: IdentityTables) -> Self {
+ pub fn new(pools: IdentityPools, config: EngineConfig, tables: IdentityTables) -> Self {
tables.validate().expect("invalid identity table set");
Self {
- pool,
+ pools,
config,
tables,
}
}
- pub fn pool(&self) -> &PgPool {
- &self.pool
+ pub fn pools(&self) -> &IdentityPools {
+ &self.pools
}
pub fn tables(&self) -> &IdentityTables {
@@ -277,7 +277,7 @@ impl Engine {
team_id as i32,
driver.initial_step(),
request
- => execute(&self.pool)
+ => execute(self.pools.fast())
)?
.rows_affected()
> 0;
@@ -328,7 +328,7 @@ impl Engine {
return Ok(row);
}
let step_start = Instant::now();
- let stepped = driver.run_step(&self.pool, &row).await;
+ let stepped = driver.run_step(&self.pools, &row).await;
record_step_duration(&row, step_start);
stepped?;
self.load(op_id).await?.ok_or_else(|| {
@@ -447,7 +447,7 @@ impl Engine {
}
let step_start = Instant::now();
- let stepped = driver.run_step(&self.pool, &row).await;
+ let stepped = driver.run_step(&self.pools, &row).await;
record_step_duration(&row, step_start);
if let Err(err) = stepped {
// Attributable escalation: a persistently failing op (a
@@ -539,7 +539,7 @@ impl Engine {
WHERE op_id = $1
"#,
op_id
- => fetch_optional(&self.pool)
+ => fetch_optional(self.pools.fast())
)
}
@@ -582,7 +582,7 @@ impl Engine {
op_id,
self.config.lease.as_secs_f64(),
unpark
- => fetch_optional(&self.pool)
+ => fetch_optional(self.pools.fast())
)
}
@@ -608,7 +608,7 @@ impl Engine {
op_id,
attempt,
reason
- => execute(&self.pool)
+ => execute(self.pools.fast())
)?
.rows_affected()
> 0;
@@ -646,7 +646,7 @@ impl Engine {
op_id,
self.config.lease.as_secs_f64(),
attempt
- => execute(&self.pool)
+ => execute(self.pools.fast())
)?;
Ok(result.rows_affected() > 0)
}
@@ -657,7 +657,7 @@ impl Engine {
"UPDATE {lifecycle_op} SET lease_expires_at = NULL WHERE op_id = $1 AND completed_at IS NULL AND attempt = $2",
op_id,
attempt
- => execute(&self.pool)
+ => execute(self.pools.fast())
)?;
Ok(())
}
@@ -682,7 +682,7 @@ impl Engine {
"#,
self.config.lease.as_secs_f64(),
SWEEP_BATCH_SIZE
- => fetch_all(&self.pool)
+ => fetch_all(self.pools.fast())
)?;
let mut resumed = 0u32;
@@ -717,7 +717,7 @@ impl Engine {
match mirrored_query_scalar!(
self.tables.is_validation(),
r#"SELECT count(*) AS "count!" FROM {lifecycle_op} WHERE completed_at IS NULL AND parked_at IS NOT NULL"#
- => fetch_one(&self.pool)
+ => fetch_one(self.pools.fast())
) {
Ok(parked) => common_metrics::gauge(OPS_PARKED, &[], parked as f64),
Err(e) => tracing::warn!(error = %e, "failed to refresh the parked-ops gauge"),
@@ -743,7 +743,7 @@ impl Engine {
"#,
retention.as_secs_f64(),
self.config.gc_batch_limit
- => execute(&self.pool)
+ => execute(self.pools.get(Lane::Heavy))
)?;
Ok(result.rows_affected())
}
diff --git a/rust/personhog-identity/src/lifecycle/merge.rs b/rust/personhog-identity/src/lifecycle/merge.rs
index 7fc9d9847b8c..9095fb95abe4 100644
--- a/rust/personhog-identity/src/lifecycle/merge.rs
+++ b/rust/personhog-identity/src/lifecycle/merge.rs
@@ -40,7 +40,6 @@ use futures::stream::{self, StreamExt};
use personhog_common::persons::person_uuid;
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use sqlx::postgres::PgPool;
use tonic::{Code, Status};
use uuid::Uuid;
@@ -55,7 +54,7 @@ use crate::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, Engine, OpDriver, OpRow, SagaError, Tx, STEP_ABORTED,
STEP_COMPLETED,
};
-use crate::storage::postgres::begin_timed;
+use crate::pools::{IdentityPools, Lane};
// Derived from the shared enum so the op-type string cannot drift from
// the leader's fence records or the lifecycle_op CHECK constraint.
@@ -135,7 +134,7 @@ pub struct MergeSourceEntry {
/// Whether another driver advanced or settled the op past our step.
async fn op_moved_on(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
op: &OpRow,
) -> Result<bool, SagaError> {
@@ -144,7 +143,7 @@ async fn op_moved_on(
tables.is_validation(),
r#"SELECT step, completed_at IS NOT NULL AS "completed!" FROM {lifecycle_op} WHERE op_id = $1"#,
op.op_id
- => fetch_optional(pool)
+ => fetch_optional(pools.fast())
)?;
Ok(match current {
// A vanished row was completed and garbage-collected.
@@ -407,7 +406,10 @@ impl MergeOpExecutor {
// See `find` for why result_large_err is allowed.
#[allow(clippy::result_large_err)]
pub async fn discard_claim_abort(&self, op_id: Uuid) -> Result<(), Status> {
- let mut tx = begin_timed(self.engine.pool())
+ let mut tx = self
+ .engine
+ .pools()
+ .begin(Lane::Fast)
.await
.map_err(|e| Status::internal(format!("discard begin failed: {e}")))?;
let tables = self.engine.tables();
@@ -482,7 +484,7 @@ impl OpDriver for MergeDriver {
MergeStep::Started.as_str()
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
let step = MergeStep::parse(&op.step).ok_or_else(|| {
SagaError::CorruptState(format!(
"merge op {} is on unknown step '{}'",
@@ -490,11 +492,11 @@ impl OpDriver for MergeDriver {
))
})?;
match step {
- MergeStep::Started => self.claim(pool, op).await,
- MergeStep::Claimed => self.seal(pool, op).await,
- MergeStep::SourcesSealed => self.fold(pool, op).await,
- MergeStep::DocumentFolded => flip(pool, &self.tables, op).await,
- MergeStep::Flipped => self.complete(pool, op).await,
+ MergeStep::Started => self.claim(pools, op).await,
+ MergeStep::Claimed => self.seal(pools, op).await,
+ MergeStep::SourcesSealed => self.fold(pools, op).await,
+ MergeStep::DocumentFolded => flip(pools, &self.tables, op).await,
+ MergeStep::Flipped => self.complete(pools, op).await,
}
}
}
@@ -610,12 +612,12 @@ impl MergeDriver {
/// still-mergeable source person via the mark index — all in one
/// transaction. Nothing outside this op's own rows is mutated, so the
/// abort branch can end the op in the same commit.
- async fn claim(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn claim(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
let team_id = op.team_id as i32;
// Conflict reasons emit only after a commit (see record_conflicts).
let mut conflicts: Vec<(&'static str, u64)> = Vec::new();
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
// Authoritative resolution: the handler's classification aged while
// the op row traveled here.
@@ -1000,9 +1002,9 @@ impl MergeDriver {
/// source, so the orphan clears via the leader's ghost-fence healer on
/// the next rejected write (or a partition handoff) — the same class
/// the takeover scan can mint, bounded the same way.
- async fn seal(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn seal(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
- let sources = live_sources(pool, &self.tables, op).await?;
+ let sources = live_sources(pools, &self.tables, op).await?;
let mut sealed: Vec<(i64, SealedSnapshot)> = Vec::new();
let mut vanished: Vec<i64> = Vec::new();
@@ -1054,7 +1056,7 @@ impl MergeDriver {
// failures retry the step; a refusal backs the op out.
return match SagaError::leader(status) {
SagaError::LeaderRefused(status) => {
- self.abort_refused(pool, op, MergeStep::Claimed, &status)
+ self.abort_refused(pools, op, MergeStep::Claimed, &status)
.await
}
err => Err(err),
@@ -1091,7 +1093,7 @@ impl MergeDriver {
.map(|s| (s.person_id, s.person_uuid))
.collect();
self.release_fences(op, &remaining).await?;
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
settle_drops(&mut tx, &self.tables, op, &vanished, &identified).await?;
abort_marks(&mut tx, &self.tables, op).await?;
let outcome =
@@ -1115,7 +1117,7 @@ impl MergeDriver {
return Ok(());
}
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
settle_drops(&mut tx, &self.tables, op, &vanished, &identified).await?;
let sealed_ids: Vec<i64> = sealed.iter().map(|(id, _)| *id).collect();
let sealed_jsons: Vec<Value> = sealed
@@ -1163,15 +1165,15 @@ impl MergeDriver {
/// before the flip, so unwinding is safe; post-flip refusals park.
async fn abort_refused(
&self,
- pool: &PgPool,
+ pools: &IdentityPools,
op: &OpRow,
from_step: MergeStep,
status: &Status,
) -> Result<(), SagaError> {
- let live = live_sources(pool, &self.tables, op).await?;
+ let live = live_sources(pools, &self.tables, op).await?;
let pairs: Vec<(i64, Uuid)> = live.iter().map(|s| (s.person_id, s.person_uuid)).collect();
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
abort_marks(&mut tx, &self.tables, op).await?;
// Fence contention never reaches this abort; it retries at the step.
let outcome = build_outcome(&mut tx, &self.tables, op, Some(AbortOutcome::Refused)).await?;
@@ -1264,7 +1266,7 @@ fn snapshot_from_sealed(person: &Person) -> Result<SealedSnapshot, SagaError> {
}
async fn live_sources(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
op: &OpRow,
) -> Result<Vec<PersonRef>, SagaError> {
@@ -1277,7 +1279,7 @@ async fn live_sources(
"#,
op.op_id,
ROLE_SOURCE
- => fetch_all(pool)
+ => fetch_all(pools.fast())
)?)
}
@@ -1357,10 +1359,10 @@ impl MergeDriver {
/// landed in between (see FoldPersonDocumentRequest.op_id in the
/// proto). The folded document persists on the target row: the
/// terminal outcome's survivor, durable without ever re-folding.
- async fn fold(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn fold(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
let request = parse_request(op)?;
- let target = target_row(pool, &self.tables, op).await?;
- let sources = sealed_sources(pool, &self.tables, op).await?;
+ let target = target_row(pools, &self.tables, op).await?;
+ let sources = sealed_sources(pools, &self.tables, op).await?;
// The fold verifies each snapshot's identity and orders by the
// ordinal itself, so the request carries the recorded pair order
@@ -1431,7 +1433,7 @@ impl MergeDriver {
// under a live claim the pre-flip abort is safe.
if personhog_common::grpc::semantic_refusal_reason(&status)
== Some("fold-unverified")
- && op_moved_on(pool, &self.tables, op).await?
+ && op_moved_on(pools, &self.tables, op).await?
{
tracing::info!(
op_id = %op.op_id,
@@ -1439,7 +1441,7 @@ impl MergeDriver {
);
Err(SagaError::Busy)
} else {
- self.abort_refused(pool, op, MergeStep::SourcesSealed, &status)
+ self.abort_refused(pools, op, MergeStep::SourcesSealed, &status)
.await
}
}
@@ -1464,7 +1466,7 @@ impl MergeDriver {
"version": folded.version,
});
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
mirrored_query!(
self.tables.is_validation(),
"UPDATE {lifecycle_op_person} SET sealed = $2 WHERE op_id = $1 AND role = $3",
@@ -1495,7 +1497,7 @@ impl MergeDriver {
}
async fn target_row(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
op: &OpRow,
) -> Result<PersonRef, SagaError> {
@@ -1505,12 +1507,12 @@ async fn target_row(
"SELECT person_id, person_uuid FROM {lifecycle_op_person} WHERE op_id = $1 AND role = $2",
op.op_id,
ROLE_TARGET
- => fetch_one(pool)
+ => fetch_one(pools.fast())
)?)
}
async fn sealed_sources(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
op: &OpRow,
) -> Result<Vec<SealedSource>, SagaError> {
@@ -1526,7 +1528,7 @@ async fn sealed_sources(
op.op_id,
ROLE_SOURCE,
STATUS_SEALED
- => fetch_all(pool)
+ => fetch_all(pools.fast())
)?)
}
@@ -1544,9 +1546,9 @@ fn encode_json_map(value: &Value) -> Result<Vec<u8>, SagaError> {
/// hash-key overrides target-wins, scrub and tombstone the source person
/// rows at their exact death versions, and clear the target's mark. The
/// source marks stay: they are the fences' durable record until release.
-async fn flip(pool: &PgPool, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
+async fn flip(pools: &IdentityPools, tables: &IdentityTables, op: &OpRow) -> Result<(), SagaError> {
let team_id = op.team_id as i32;
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
let target: i64 = mirrored_query_scalar!(
tables.is_validation(),
@@ -1828,8 +1830,8 @@ impl MergeDriver {
/// release ack, because to the leader a `deleted` mark means "the
/// death document already exists; absorb the retry". Flipping first
/// would make the first-ever release absorb and never produce.
- async fn complete(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
- let sources = sealed_sources(pool, &self.tables, op).await?;
+ async fn complete(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
+ let sources = sealed_sources(pools, &self.tables, op).await?;
let release_calls: Vec<_> = sources
.iter()
@@ -1878,7 +1880,7 @@ impl MergeDriver {
result?;
}
- let mut tx = begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
mirrored_query!(
self.tables.is_validation(),
r#"
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 136b2fd61a4f..00b3667cc014 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -3,7 +3,7 @@ use std::time::Duration;
use assignment_coordination::store::{EtcdStore, StoreConfig};
use axum::{routing::get, Router};
-use common_database::{get_pool_with_config, PoolConfig};
+use common_database::get_pool_with_config;
use envconfig::Envconfig;
use lifecycle::{ComponentOptions, Manager};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
@@ -11,6 +11,7 @@ use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetric
use personhog_common::{spawn_pool_monitor, MonitoredPool};
use personhog_proto::personhog::identity::v1::person_hog_identity_server::PersonHogIdentityServer;
use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycleServer;
+use sqlx::postgres::PgPool;
use tonic::codec::CompressionEncoding;
use tonic::transport::Server;
use tracing::level_filters::LevelFilter;
@@ -27,28 +28,65 @@ use personhog_identity::lifecycle::delete::DeleteDriver;
use personhog_identity::lifecycle::engine::Engine;
use personhog_identity::lifecycle::merge::{MergeDriver, MergeOpExecutor};
use personhog_identity::lifecycle::PersonHogLifecycleService;
+use personhog_identity::pools::{IdentityPools, Lane};
use personhog_identity::service::merge::MergeEntrance;
use personhog_identity::service::PersonHogIdentityService;
use personhog_identity::storage::postgres::PostgresIdentityStorage;
common_alloc::used!();
-fn create_storage(config: &Config) -> Arc<PostgresIdentityStorage> {
- let primary_pool_config = PoolConfig {
- min_connections: config.min_pg_connections,
- max_connections: config.max_pg_connections,
- acquire_timeout: config.acquire_timeout(),
- idle_timeout: config.idle_timeout(),
- test_before_acquire: false,
- statement_timeout_ms: config.statement_timeout(),
- pool_name: Some("primary".to_string()),
- };
-
- let primary_pool = get_pool_with_config(&config.primary_database_url, primary_pool_config)
- .expect("Failed to create primary database pool");
- tracing::info!("Created primary database pool");
+fn create_pools(config: &Config) -> IdentityPools {
+ let fast = get_pool_with_config(&config.primary_database_url, config.fast_pool_config())
+ .expect("Failed to create fast database pool");
+ let heavy = get_pool_with_config(&config.primary_database_url, config.heavy_pool_config())
+ .expect("Failed to create heavy database pool");
+ tracing::info!("Created fast and heavy database pools");
+ IdentityPools::new(fast, heavy)
+}
- Arc::new(PostgresIdentityStorage::new(primary_pool, config.tables()))
+/// Hold `min_connections` connections and run a query on `server_warmup`
+/// of them. acquire() only establishes app → PgBouncer; in transaction
+/// pooling mode PgBouncer doesn't open a server connection until a query
+/// runs.
+async fn warm_pool(pool: &PgPool, lane: Lane, min_connections: u32, server_warmup: u32) {
+ if min_connections == 0 {
+ return;
+ }
+ let warmup_count = min_connections as usize;
+ let server_warmup_count = (server_warmup as usize).min(warmup_count);
+ tracing::info!(
+ pool = lane.label(),
+ count = warmup_count,
+ server_warmup = server_warmup_count,
+ "Warming database connection pool before accepting traffic"
+ );
+ let pool_start = std::time::Instant::now();
+ let mut conns = Vec::with_capacity(warmup_count);
+ for _ in 0..warmup_count {
+ match pool.acquire().await {
+ Ok(conn) => conns.push(conn),
+ Err(e) => {
+ tracing::warn!(pool = lane.label(), error = %e, "Failed to warm connection");
+ break;
+ }
+ }
+ }
+ let mut server_warmed = 0u32;
+ for conn in conns.iter_mut().take(server_warmup_count) {
+ match sqlx::query("SELECT 1").execute(&mut **conn).await {
+ Ok(_) => server_warmed += 1,
+ Err(e) => {
+ tracing::warn!(pool = lane.label(), error = %e, "Failed to warm server-side connection");
+ }
+ }
+ }
+ tracing::info!(
+ pool = lane.label(),
+ client_conns = conns.len(),
+ server_conns = server_warmed,
+ elapsed_ms = pool_start.elapsed().as_millis() as u64,
+ "Pool warmup complete"
+ );
}
#[tokio::main]
@@ -183,57 +221,41 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.expect("Metrics server error");
});
- let storage = create_storage(&config);
+ let pools = create_pools(&config);
+ let storage = Arc::new(PostgresIdentityStorage::new(pools.clone(), config.tables()));
- // Pre-warm the DB connection pool before accepting traffic.
+ // Pre-warm the DB connection pools before accepting traffic.
// connect_lazy() starts with zero connections; without this, the first
// burst of requests after K8s routes traffic all pay the cold-start cost.
// Warming here is safe because the gRPC server hasn't bound its port yet.
- if config.min_pg_connections > 0 {
- let warmup_count = config.min_pg_connections as usize;
- let server_warmup_count = (config.warmup_server_connections as usize).min(warmup_count);
- tracing::info!(
- count = warmup_count,
- server_warmup = server_warmup_count,
- "Warming database connection pool before accepting traffic"
- );
- let pool_start = std::time::Instant::now();
- let mut conns = Vec::with_capacity(warmup_count);
- for _ in 0..warmup_count {
- match storage.primary_pool.acquire().await {
- Ok(conn) => conns.push(conn),
- Err(e) => {
- tracing::warn!(error = %e, "Failed to warm connection");
- break;
- }
- }
- }
- // Run a query on a subset of held connections to warm PgBouncer → PG.
- // acquire() only establishes app → PgBouncer; in transaction pooling
- // mode PgBouncer doesn't open a server connection until a query runs.
- let mut server_warmed = 0u32;
- for conn in conns.iter_mut().take(server_warmup_count) {
- match sqlx::query("SELECT 1").execute(&mut **conn).await {
- Ok(_) => server_warmed += 1,
- Err(e) => {
- tracing::warn!(error = %e, "Failed to warm server-side connection");
- }
- }
- }
- tracing::info!(
- client_conns = conns.len(),
- server_conns = server_warmed,
- elapsed_ms = pool_start.elapsed().as_millis() as u64,
- "Pool warmup complete"
- );
- }
+ warm_pool(
+ pools.fast(),
+ Lane::Fast,
+ config.min_pg_connections,
+ config.warmup_server_connections,
+ )
+ .await;
+ warm_pool(
+ pools.heavy(),
+ Lane::Heavy,
+ config.heavy_min_pg_connections,
+ config.warmup_server_connections,
+ )
+ .await;
spawn_pool_monitor(
- vec![MonitoredPool {
- pool: storage.primary_pool.clone(),
- label: "primary".to_string(),
- max_connections: config.max_pg_connections,
- }],
+ vec![
+ MonitoredPool {
+ pool: pools.fast().clone(),
+ label: Lane::Fast.label().to_string(),
+ max_connections: config.max_pg_connections,
+ },
+ MonitoredPool {
+ pool: pools.heavy().clone(),
+ label: Lane::Heavy.label().to_string(),
+ max_connections: config.heavy_max_pg_connections,
+ },
+ ],
Duration::from_secs(config.pool_monitor_interval_secs),
);
@@ -250,7 +272,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// property writes.
let lifecycle_leader: Arc<dyn LifecycleLeader> = property_writer.clone();
let engine = Arc::new(Engine::new(
- storage.primary_pool.clone(),
+ pools.clone(),
config.lifecycle_engine_config(),
config.tables(),
));
diff --git a/rust/personhog-identity/src/pools.rs b/rust/personhog-identity/src/pools.rs
new file mode 100644
index 000000000000..110fef4d6129
--- /dev/null
+++ b/rust/personhog-identity/src/pools.rs
@@ -0,0 +1,96 @@
+//! The two Postgres pools identity runs on, split by how long a statement
+//! holds its connection. Fast: the request path's reads and the lifecycle
+//! engine's single-row op bookkeeping, sub-millisecond and never waiting
+//! on a person row lock. Heavy: stub creation, distinct id attach, every
+//! saga step transaction, and GC, which hold a connection for tens to
+//! hundreds of milliseconds and, under lock contention, up to the
+//! statement timeout. On one shared pool a burst of heavy statements took
+//! every slot the resolves behind them needed.
+
+use std::time::Instant;
+
+use sqlx::pool::PoolConnection;
+use sqlx::postgres::PgPool;
+use sqlx::{Postgres, Transaction};
+
+use personhog_common::grpc::{current_client_name, current_method_name};
+
+const DB_POOL_ACQUIRE_DURATION: &str = "personhog_identity_db_pool_acquire_duration_ms";
+
+/// Which pool a statement runs on; doubles as the `pool` metric label.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Lane {
+ Fast,
+ Heavy,
+}
+
+impl Lane {
+ pub fn label(self) -> &'static str {
+ match self {
+ Lane::Fast => "fast",
+ Lane::Heavy => "heavy",
+ }
+ }
+}
+
+#[derive(Clone)]
+pub struct IdentityPools {
+ fast: PgPool,
+ heavy: PgPool,
+}
+
+impl IdentityPools {
+ pub fn new(fast: PgPool, heavy: PgPool) -> Self {
+ Self { fast, heavy }
+ }
+
+ /// One pool behind both lanes, for tests and tooling that run against
+ /// a single connection string.
+ pub fn shared(pool: PgPool) -> Self {
+ Self {
+ fast: pool.clone(),
+ heavy: pool,
+ }
+ }
+
+ pub fn fast(&self) -> &PgPool {
+ &self.fast
+ }
+
+ pub fn heavy(&self) -> &PgPool {
+ &self.heavy
+ }
+
+ pub fn get(&self, lane: Lane) -> &PgPool {
+ match lane {
+ Lane::Fast => &self.fast,
+ Lane::Heavy => &self.heavy,
+ }
+ }
+
+ pub async fn acquire(&self, lane: Lane) -> sqlx::Result<PoolConnection<Postgres>> {
+ let start = Instant::now();
+ let conn = self.get(lane).acquire().await;
+ record_acquire(lane, start);
+ conn
+ }
+
+ pub async fn begin(&self, lane: Lane) -> sqlx::Result<Transaction<'_, Postgres>> {
+ let start = Instant::now();
+ let tx = self.get(lane).begin().await;
+ record_acquire(lane, start);
+ tx
+ }
+}
+
+fn record_acquire(lane: Lane, start: Instant) {
+ common_metrics::histogram(
+ DB_POOL_ACQUIRE_DURATION,
+ &[
+ ("pool".to_string(), lane.label().to_string()),
+ ("client".to_string(), current_client_name().to_string()),
+ ("method".to_string(), current_method_name().to_string()),
+ ],
+ start.elapsed().as_secs_f64() * 1000.0,
+ );
+}
diff --git a/rust/personhog-identity/src/storage/postgres/attach.rs b/rust/personhog-identity/src/storage/postgres/attach.rs
index c368cb20572d..efc5b2f54fc8 100644
--- a/rust/personhog-identity/src/storage/postgres/attach.rs
+++ b/rust/personhog-identity/src/storage/postgres/attach.rs
@@ -3,10 +3,10 @@
use std::collections::HashMap;
-use sqlx::postgres::PgPool;
use sqlx::Row;
use crate::config::IdentityTables;
+use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::types::AttachOutcome;
@@ -21,7 +21,7 @@ use crate::storage::types::AttachOutcome;
/// check rejects persons held by a live op. The rare statement that slips
/// both leaves an orphaned mapping the next resolve treats as absent.
pub(super) async fn attach_distinct_ids(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
team_id: i64,
person_id: i64,
@@ -56,7 +56,7 @@ pub(super) async fn attach_distinct_ids(
person = tables.person,
lop = tables.lifecycle_op_person,
);
- let mut conn = super::acquire_timed(pool).await?;
+ let mut conn = pools.acquire(Lane::Heavy).await?;
let written = sqlx::query(&insert_sql)
.bind(&sorted)
.bind(person_id)
diff --git a/rust/personhog-identity/src/storage/postgres/mod.rs b/rust/personhog-identity/src/storage/postgres/mod.rs
index 4e61dd01185c..414159fdd0f5 100644
--- a/rust/personhog-identity/src/storage/postgres/mod.rs
+++ b/rust/personhog-identity/src/storage/postgres/mod.rs
@@ -8,54 +8,19 @@ mod resolve;
mod stub_create;
use std::collections::HashMap;
-use std::time::Instant;
use async_trait::async_trait;
-use sqlx::pool::PoolConnection;
-use sqlx::postgres::{PgPool, PgRow};
-use sqlx::{Postgres, Row, Transaction};
+use sqlx::postgres::PgRow;
+use sqlx::Row;
use personhog_common::grpc::{current_client_name, current_method_name};
use crate::config::IdentityTables;
+use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::types::{AttachOutcome, DistinctIdMapping, Person, PersonStub, StubOutcome};
use crate::storage::{IdentityStorage, DB_QUERY_DURATION};
-const POOL_LABEL: &str = "primary";
-
-/// Wait for a pool connection. Connection churn shows up here while
-/// every other layer reads idle.
-const DB_POOL_ACQUIRE_DURATION: &str = "personhog_identity_db_pool_acquire_duration_ms";
-
-fn record_acquire(start: Instant) {
- common_metrics::histogram(
- DB_POOL_ACQUIRE_DURATION,
- &[
- ("pool".to_string(), POOL_LABEL.to_string()),
- ("client".to_string(), current_client_name().to_string()),
- ("method".to_string(), current_method_name().to_string()),
- ],
- start.elapsed().as_secs_f64() * 1000.0,
- );
-}
-
-/// Acquire a primary connection, recording the wait.
-pub(super) async fn acquire_timed(pool: &PgPool) -> sqlx::Result<PoolConnection<Postgres>> {
- let start = Instant::now();
- let conn = pool.acquire().await;
- record_acquire(start);
- conn
-}
-
-/// Begin a primary transaction, recording the acquire wait it contains.
-pub(crate) async fn begin_timed(pool: &PgPool) -> sqlx::Result<Transaction<'_, Postgres>> {
- let start = Instant::now();
- let tx = pool.begin().await;
- record_acquire(start);
- tx
-}
-
/// Decode a person from a row whose SELECT list uses the canonical aliases
/// (`team_id::bigint AS team_id`, the `is_user_id` boolean CASE, …). Shared
/// by every submodule that selects person rows — the table name is
@@ -93,23 +58,20 @@ pub(super) fn person_columns(p: &str) -> String {
}
pub struct PostgresIdentityStorage {
- pub primary_pool: PgPool,
+ pools: IdentityPools,
tables: IdentityTables,
}
impl PostgresIdentityStorage {
- pub fn new(primary_pool: PgPool, tables: IdentityTables) -> Self {
+ pub fn new(pools: IdentityPools, tables: IdentityTables) -> Self {
tables.validate().expect("invalid identity table set");
- Self {
- primary_pool,
- tables,
- }
+ Self { pools, tables }
}
- fn query_labels(operation: &str) -> [(String, String); 4] {
+ fn query_labels(operation: &str, lane: Lane) -> [(String, String); 4] {
[
("operation".to_string(), operation.to_string()),
- ("pool".to_string(), POOL_LABEL.to_string()),
+ ("pool".to_string(), lane.label().to_string()),
("client".to_string(), current_client_name().to_string()),
("method".to_string(), current_method_name().to_string()),
]
@@ -122,9 +84,9 @@ impl IdentityStorage for PostgresIdentityStorage {
&self,
keys: &[(i64, String)],
) -> StorageResult<HashMap<(i64, String), Person>> {
- let labels = Self::query_labels("resolve_distinct_ids");
+ let labels = Self::query_labels("resolve_distinct_ids", Lane::Fast);
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- resolve::resolve_distinct_ids(&self.primary_pool, &self.tables, keys).await
+ resolve::resolve_distinct_ids(&self.pools, &self.tables, keys).await
}
async fn get_distinct_ids_for_persons(
@@ -133,10 +95,10 @@ impl IdentityStorage for PostgresIdentityStorage {
person_ids: &[i64],
limit_per_person: Option<i64>,
) -> StorageResult<Vec<DistinctIdMapping>> {
- let labels = Self::query_labels("get_distinct_ids_for_persons");
+ let labels = Self::query_labels("get_distinct_ids_for_persons", Lane::Fast);
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
distinct_ids::get_distinct_ids_for_persons(
- &self.primary_pool,
+ self.pools.fast(),
&self.tables.person_distinct_id,
team_id,
person_ids,
@@ -146,9 +108,9 @@ impl IdentityStorage for PostgresIdentityStorage {
}
async fn create_person_stubs(&self, stubs: &[PersonStub]) -> StorageResult<Vec<StubOutcome>> {
- let labels = Self::query_labels("create_person_stubs");
+ let labels = Self::query_labels("create_person_stubs", Lane::Heavy);
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- stub_create::create_person_stubs(&self.primary_pool, &self.tables, stubs).await
+ stub_create::create_person_stubs(&self.pools, &self.tables, stubs).await
}
async fn attach_distinct_ids(
@@ -157,15 +119,9 @@ impl IdentityStorage for PostgresIdentityStorage {
person_id: i64,
distinct_ids: &[String],
) -> StorageResult<HashMap<String, AttachOutcome>> {
- let labels = Self::query_labels("attach_distinct_ids");
+ let labels = Self::query_labels("attach_distinct_ids", Lane::Heavy);
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
- attach::attach_distinct_ids(
- &self.primary_pool,
- &self.tables,
- team_id,
- person_id,
- distinct_ids,
- )
- .await
+ attach::attach_distinct_ids(&self.pools, &self.tables, team_id, person_id, distinct_ids)
+ .await
}
}
diff --git a/rust/personhog-identity/src/storage/postgres/resolve.rs b/rust/personhog-identity/src/storage/postgres/resolve.rs
index 6c78e2346df0..0003cefea89f 100644
--- a/rust/personhog-identity/src/storage/postgres/resolve.rs
+++ b/rust/personhog-identity/src/storage/postgres/resolve.rs
@@ -1,9 +1,9 @@
use std::collections::HashMap;
-use sqlx::postgres::PgPool;
use sqlx::Row;
use crate::config::IdentityTables;
+use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::postgres::{person_columns, person_from_row};
use crate::storage::types::Person;
@@ -12,7 +12,7 @@ use crate::storage::types::Person;
/// primary. Tombstoned mappings and persons are invisible; unresolved keys
/// are absent from the result.
pub(super) async fn resolve_distinct_ids(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
keys: &[(i64, String)],
) -> StorageResult<HashMap<(i64, String), Person>> {
@@ -39,7 +39,7 @@ pub(super) async fn resolve_distinct_ids(
pdi_table = tables.person_distinct_id,
person_table = tables.person,
);
- let mut conn = super::acquire_timed(pool).await?;
+ let mut conn = pools.acquire(Lane::Fast).await?;
let rows = sqlx::query(&sql)
.bind(&team_ids)
.bind(&distinct_ids)
diff --git a/rust/personhog-identity/src/storage/postgres/stub_create.rs b/rust/personhog-identity/src/storage/postgres/stub_create.rs
index 3b403ce85824..7c3194d855ee 100644
--- a/rust/personhog-identity/src/storage/postgres/stub_create.rs
+++ b/rust/personhog-identity/src/storage/postgres/stub_create.rs
@@ -26,13 +26,13 @@
use std::collections::{HashMap, HashSet};
use chrono::{DateTime, Utc};
-use sqlx::postgres::PgPool;
use sqlx::Row;
use uuid::Uuid;
use personhog_common::persons::person_uuid;
use crate::config::IdentityTables;
+use crate::pools::{IdentityPools, Lane};
use crate::storage::error::StorageResult;
use crate::storage::postgres::{person_columns, person_from_row};
use crate::storage::types::{Person, PersonStub, StubOutcome};
@@ -67,7 +67,7 @@ struct MappingOutcome {
}
pub(super) async fn create_person_stubs(
- pool: &PgPool,
+ pools: &IdentityPools,
tables: &IdentityTables,
stubs: &[PersonStub],
) -> StorageResult<Vec<StubOutcome>> {
@@ -83,7 +83,7 @@ pub(super) async fn create_person_stubs(
.collect();
let team_ids: Vec<i32> = stubs.iter().map(|s| s.team_id as i32).collect();
- let mut tx = super::begin_timed(pool).await?;
+ let mut tx = pools.begin(Lane::Heavy).await?;
let mut persons = insert_or_revive_persons(&mut tx, tables, stubs, &team_ids, &uuids).await?;
fetch_conflict_winners(
diff --git a/rust/personhog-identity/tests/common/mod.rs b/rust/personhog-identity/tests/common/mod.rs
index a0958f703a2d..72d13f28306d 100644
--- a/rust/personhog-identity/tests/common/mod.rs
+++ b/rust/personhog-identity/tests/common/mod.rs
@@ -10,6 +10,7 @@ use rand::Rng;
use sqlx::postgres::PgPool;
use personhog_identity::config::IdentityTables;
+use personhog_identity::pools::IdentityPools;
use personhog_identity::storage::postgres::PostgresIdentityStorage;
/// The production table set. Most tests run here; the raw-SQL assertion
@@ -30,6 +31,7 @@ pub fn tmp_tables() -> IdentityTables {
pub struct TestContext {
pub pool: PgPool,
+ pub pools: IdentityPools,
pub storage: Arc<PostgresIdentityStorage>,
pub team_id: i64,
pub tables: IdentityTables,
@@ -47,10 +49,12 @@ impl TestContext {
let pool = PgPool::connect(&database_url)
.await
.expect("Failed to connect to test database");
- let storage = Arc::new(PostgresIdentityStorage::new(pool.clone(), tables.clone()));
+ let pools = IdentityPools::shared(pool.clone());
+ let storage = Arc::new(PostgresIdentityStorage::new(pools.clone(), tables.clone()));
let team_id = rand::thread_rng().gen_range(1_000_000..100_000_000);
Self {
pool,
+ pools,
storage,
team_id,
tables,
@@ -102,7 +106,7 @@ impl TestContext {
/// explicit lease_expires_at values instead of waiting this out.
pub fn engine(&self) -> personhog_identity::lifecycle::engine::Engine {
personhog_identity::lifecycle::engine::Engine::new(
- self.pool.clone(),
+ self.pools.clone(),
personhog_identity::lifecycle::engine::EngineConfig {
lease: std::time::Duration::from_secs(300),
execute_timeout: std::time::Duration::from_secs(10),
diff --git a/rust/personhog-identity/tests/lifecycle_engine_tests.rs b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
index ed857e06f008..50fa3c3c5e59 100644
--- a/rust/personhog-identity/tests/lifecycle_engine_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_engine_tests.rs
@@ -25,6 +25,7 @@ use personhog_common::grpc::semantic_refusal;
use personhog_identity::lifecycle::engine::{
advance_step_in_tx, complete_op_in_tx, OpDriver, OpRow, SagaError, STEP_COMPLETED,
};
+use personhog_identity::pools::IdentityPools;
/// Two-step dummy op: `started → half → completed`. Counts step executions
/// so tests can prove what did (or did not) re-run.
@@ -50,9 +51,9 @@ impl OpDriver for DummyDriver {
"started"
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
self.steps_run.fetch_add(1, Ordering::SeqCst);
- let mut tx = pool.begin().await.map_err(SagaError::Db)?;
+ let mut tx = pools.heavy().begin().await.map_err(SagaError::Db)?;
let advanced = match op.step.as_str() {
"started" => {
advance_step_in_tx(
@@ -308,7 +309,7 @@ async fn a_live_lease_blocks_a_second_driver_until_it_lapses() {
.expect("insert leased op");
let short_engine = personhog_identity::lifecycle::engine::Engine::new(
- ctx.pool.clone(),
+ ctx.pools.clone(),
personhog_identity::lifecycle::engine::EngineConfig {
lease: std::time::Duration::from_secs(5),
execute_timeout: std::time::Duration::from_millis(200),
@@ -346,7 +347,7 @@ impl OpDriver for SlowDriver {
"started"
}
- async fn run_step(&self, _pool: &PgPool, _op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, _pools: &IdentityPools, _op: &OpRow) -> Result<(), SagaError> {
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
Ok(())
}
@@ -358,7 +359,7 @@ async fn a_drive_that_runs_out_its_own_deadline_says_so_and_releases_the_lease()
let op_id = Uuid::now_v7();
let short_engine = personhog_identity::lifecycle::engine::Engine::new(
- ctx.pool.clone(),
+ ctx.pools.clone(),
personhog_identity::lifecycle::engine::EngineConfig {
lease: std::time::Duration::from_secs(5),
execute_timeout: std::time::Duration::from_millis(200),
@@ -466,9 +467,9 @@ impl OpDriver for StolenLeaseDriver {
"started"
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
self.steps_run.fetch_add(1, Ordering::SeqCst);
- steal_lease(pool, op.op_id).await;
+ steal_lease(pools.fast(), op.op_id).await;
if self.fail_after_steal {
Err(SagaError::CorruptState("simulated step failure".into()))
} else {
@@ -487,7 +488,7 @@ async fn a_driver_whose_lease_was_stolen_stops_running_steps_instead_of_renewing
let op_id = Uuid::now_v7();
let short_engine = personhog_identity::lifecycle::engine::Engine::new(
- ctx.pool.clone(),
+ ctx.pools.clone(),
personhog_identity::lifecycle::engine::EngineConfig {
lease: std::time::Duration::from_secs(5),
execute_timeout: std::time::Duration::from_millis(200),
@@ -567,7 +568,7 @@ impl OpDriver for RefusingDriver {
"started"
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
self.steps_run.fetch_add(1, Ordering::SeqCst);
if self
.refusals_left
@@ -579,7 +580,7 @@ impl OpDriver for RefusingDriver {
"test-refusal",
)));
}
- let mut tx = pool.begin().await.map_err(SagaError::Db)?;
+ let mut tx = pools.heavy().begin().await.map_err(SagaError::Db)?;
let advanced = complete_op_in_tx(
&mut tx,
&common::default_tables(),
@@ -667,8 +668,8 @@ impl OpDriver for StolenLeaseRefusingDriver {
"started"
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
- steal_lease(pool, op.op_id).await;
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
+ steal_lease(pools.fast(), op.op_id).await;
Err(SagaError::leader(semantic_refusal(
"injected refusal",
"test-refusal",
@@ -833,11 +834,11 @@ impl OpDriver for DeadlockingDriver {
"started"
}
- async fn run_step(&self, pool: &PgPool, op: &OpRow) -> Result<(), SagaError> {
+ async fn run_step(&self, pools: &IdentityPools, op: &OpRow) -> Result<(), SagaError> {
if self.attempts.fetch_add(1, Ordering::SeqCst) < self.fail_first {
return Err(db_error("40P01"));
}
- self.inner.run_step(pool, op).await
+ self.inner.run_step(pools, op).await
}
}
diff --git a/rust/personhog-identity/tests/lifecycle_merge_tests.rs b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
index 3f758f3b129e..5e904ed8af0c 100644
--- a/rust/personhog-identity/tests/lifecycle_merge_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_merge_tests.rs
@@ -1029,7 +1029,7 @@ async fn a_stale_drivers_fold_refusal_defers_instead_of_unfencing_the_new_owners
// could land and be destroyed. The stale drive defers to the row.
let err = h
.driver
- .run_step(&h.ctx.pool, &stale_row)
+ .run_step(&h.ctx.pools, &stale_row)
.await
.expect_err("the stale drive defers rather than settling");
assert!(matches!(err, SagaError::Busy));
@@ -1091,7 +1091,7 @@ async fn the_sweeper_drives_an_abandoned_merge_to_completion() {
.expect("insert parked op");
let sweep_engine = Engine::new(
- h.ctx.pool.clone(),
+ h.ctx.pools.clone(),
personhog_identity::lifecycle::engine::EngineConfig {
lease: std::time::Duration::from_secs(3600),
execute_timeout: std::time::Duration::from_secs(10),
diff --git a/rust/personhog-identity/tests/lifecycle_service_tests.rs b/rust/personhog-identity/tests/lifecycle_service_tests.rs
index 31eb16b06815..1cd5fa457d23 100644
--- a/rust/personhog-identity/tests/lifecycle_service_tests.rs
+++ b/rust/personhog-identity/tests/lifecycle_service_tests.rs
@@ -11,6 +11,7 @@ use personhog_identity::config::IdentityTables;
use personhog_identity::lifecycle::engine::{Engine, EngineConfig};
use personhog_identity::lifecycle::validation::MAX_DELETE_BATCH_SIZE;
use personhog_identity::lifecycle::PersonHogLifecycleService;
+use personhog_identity::pools::IdentityPools;
use personhog_proto::personhog::lifecycle::v1::person_hog_lifecycle_server::PersonHogLifecycle;
use personhog_proto::personhog::lifecycle::v1::DeletePersonsRequest;
@@ -29,7 +30,7 @@ async fn delete_status(request: DeletePersonsRequest) -> Code {
.connect_lazy("postgres://unused:unused@localhost:1/unused")
.expect("lazy pool never connects");
let engine = Arc::new(Engine::new(
- pool.clone(),
+ IdentityPools::shared(pool.clone()),
EngineConfig {
lease: Duration::from_secs(1),
execute_timeout: Duration::from_secs(1),