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): pool the router's grpc connections per leader pod (#109476)

Nick Best31adc00c0a98
diff --git a/rust/personhog-router/src/backend/leader.rs b/rust/personhog-router/src/backend/leader.rs
index b8713cc9aeb1..c9d60e6015c2 100644
--- a/rust/personhog-router/src/backend/leader.rs
+++ b/rust/personhog-router/src/backend/leader.rs
@@ -1,4 +1,5 @@
use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -118,9 +119,22 @@ pub enum ForwardDecision {
pub struct LeaderBackendConfig {
pub num_partitions: u32,
pub timeout: Duration,
+ pub num_channels: usize,
pub http2_windows: Http2Windows,
}
+struct ChannelPool {
+ channels: Box<[Channel]>,
+ next: AtomicUsize,
+}
+
+impl ChannelPool {
+ fn next_channel(&self) -> Channel {
+ let idx = self.next.fetch_add(1, Ordering::Relaxed) % self.channels.len();
+ self.channels[idx].clone()
+ }
+}
+
/// Backend that routes person writes and strong reads to leader pods
/// based on Kafka-compatible partitioning of person_id.
pub struct LeaderBackend {
@@ -129,7 +143,7 @@ pub struct LeaderBackend {
/// Cached gRPC channels keyed by pod gRPC address. All leader traffic —
/// strong reads and writes — forwards raw request frames over these
/// channels.
- channels: DashMap<String, Channel>,
+ channels: DashMap<String, Arc<ChannelPool>>,
/// Resolves pod_name → gRPC address.
address_resolver: AddressResolver,
config: LeaderBackendConfig,
@@ -214,26 +228,29 @@ impl LeaderBackend {
Status::unavailable(format!("cannot resolve address for pod {pod_name}"))
})?;
- if let Some(channel) = self.channels.get(&address) {
- return Ok(channel.clone());
- }
-
- // The connect deadline matters independently of the request
- // timeout: dialing a pod whose IP has been unassigned black-holes
- // at TCP connect (no RST ever arrives), and the request timeout
- // only starts once a connection exists.
- let endpoint = Channel::from_shared(address.clone())
- .map_err(|e| Status::internal(format!("invalid leader address: {e}")))?
- .timeout(self.config.timeout)
- .connect_timeout(self.config.timeout)
- .tcp_nodelay(true);
- let channel = self
- .config
- .http2_windows
- .apply_to_endpoint(endpoint)
- .connect_lazy();
- self.channels.insert(address, channel.clone());
- Ok(channel)
+ let pool = match self.channels.get(&address) {
+ Some(pool) => Arc::clone(&pool),
+ None => {
+ // The connect deadline matters independently of the request
+ // timeout: dialing a pod whose IP has been unassigned black-holes
+ // at TCP connect (no RST ever arrives), and the request timeout
+ // only starts once a connection exists.
+ let endpoint = Channel::from_shared(address.clone())
+ .map_err(|e| Status::internal(format!("invalid leader address: {e}")))?
+ .timeout(self.config.timeout)
+ .connect_timeout(self.config.timeout)
+ .tcp_nodelay(true);
+ let endpoint = self.config.http2_windows.apply_to_endpoint(endpoint);
+ let pool = Arc::new(ChannelPool {
+ channels: (0..self.config.num_channels.max(1))
+ .map(|_| endpoint.connect_lazy())
+ .collect(),
+ next: AtomicUsize::new(0),
+ });
+ Arc::clone(&self.channels.entry(address).or_insert(pool))
+ }
+ };
+ Ok(pool.next_channel())
}
/// Send a raw gRPC request frame over an already-resolved channel —
@@ -531,10 +548,40 @@ mod tests {
LeaderBackendConfig {
num_partitions,
timeout: Duration::from_secs(5),
+ num_channels: 4,
http2_windows: Http2Windows::default(),
}
}
+ async fn assigned_backend(num_channels: usize) -> (LeaderBackend, u32) {
+ let routing_table = Arc::new(RwLock::new(HashMap::new()));
+ let resolver: AddressResolver =
+ Arc::new(|pod_name| Some(format!("http://{pod_name}:50053")));
+ let backend = LeaderBackend::new(
+ Arc::clone(&routing_table),
+ resolver,
+ LeaderBackendConfig {
+ num_channels,
+ ..test_config(8)
+ },
+ StashTable::with_bounds(usize::MAX, usize::MAX),
+ );
+ let partition = backend.partition_for_person(1, 42);
+ routing_table
+ .write()
+ .await
+ .insert(partition, "leader-0".to_string());
+ (backend, partition)
+ }
+
+ fn pool_state(backend: &LeaderBackend, pod_name: &str) -> (usize, usize) {
+ let pool = backend
+ .channels
+ .get(&format!("http://{pod_name}:50053"))
+ .unwrap();
+ (pool.channels.len(), pool.next.load(Ordering::Relaxed))
+ }
+
#[tokio::test]
async fn resolve_leader_returns_unavailable_when_no_assignment() {
let routing_table = Arc::new(RwLock::new(HashMap::new()));
@@ -631,22 +678,8 @@ mod tests {
#[tokio::test]
async fn resolve_leader_caches_channel() {
- let routing_table = Arc::new(RwLock::new(HashMap::new()));
- let resolver: AddressResolver = Arc::new(|_| Some("http://localhost:50053".to_string()));
- let backend = LeaderBackend::new(
- Arc::clone(&routing_table),
- resolver,
- test_config(8),
- StashTable::with_bounds(usize::MAX, usize::MAX),
- );
-
- let partition = backend.partition_for_person(1, 42);
- routing_table
- .write()
- .await
- .insert(partition, "leader-0".to_string());
+ let (backend, partition) = assigned_backend(4).await;
- let partition = backend.partition_for_person(1, 42);
let _channel1 = backend.resolve_leader_channel(partition).await.unwrap();
assert_eq!(backend.channels.len(), 1);
@@ -654,6 +687,61 @@ mod tests {
assert_eq!(backend.channels.len(), 1); // still 1, cached
}
+ #[tokio::test]
+ async fn resolve_leader_cycles_through_the_pods_whole_pool() {
+ for num_channels in [1usize, 4] {
+ let (backend, partition) = assigned_backend(num_channels).await;
+ for turn in 0..(2 * num_channels) {
+ backend.resolve_leader_channel(partition).await.unwrap();
+ assert_eq!(
+ pool_state(&backend, "leader-0"),
+ (num_channels, turn + 1),
+ "{num_channels} channels, turn {turn}"
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn each_pod_cycles_its_own_pool() {
+ let (backend, partition_a) = assigned_backend(4).await;
+ let partition_b = (partition_a + 1) % 8;
+ backend
+ .routing_table
+ .write()
+ .await
+ .insert(partition_b, "leader-1".to_string());
+
+ for _ in 0..2 {
+ backend.resolve_leader_channel(partition_a).await.unwrap();
+ backend.resolve_leader_channel(partition_b).await.unwrap();
+ }
+ assert_eq!(pool_state(&backend, "leader-0"), (4, 2));
+ assert_eq!(pool_state(&backend, "leader-1"), (4, 2));
+ }
+
+ #[tokio::test]
+ async fn a_zero_pool_size_still_opens_one_channel() {
+ let (backend, partition) = assigned_backend(0).await;
+ backend.resolve_leader_channel(partition).await.unwrap();
+ assert_eq!(pool_state(&backend, "leader-0"), (1, 1));
+ }
+
+ #[tokio::test]
+ async fn clear_client_cache_drops_the_whole_pool() {
+ let (backend, partition) = assigned_backend(4).await;
+ for _ in 0..3 {
+ backend.resolve_leader_channel(partition).await.unwrap();
+ }
+ assert_eq!(backend.channels.len(), 1);
+
+ backend.clear_client_cache("leader-0");
+ assert!(backend.channels.is_empty());
+
+ backend.resolve_leader_channel(partition).await.unwrap();
+ assert_eq!(pool_state(&backend, "leader-0"), (4, 1));
+ }
+
/// When the partition's stash is open and full, `forward_or_stash`
/// must short-circuit with an UNAVAILABLE gRPC response instead of
/// forwarding, so callers see a retryable status rather than getting
diff --git a/rust/personhog-router/src/config.rs b/rust/personhog-router/src/config.rs
index 6c3ea822487a..00307fb7b5bb 100644
--- a/rust/personhog-router/src/config.rs
+++ b/rust/personhog-router/src/config.rs
@@ -142,6 +142,10 @@ pub struct Config {
#[envconfig(default = "30000")]
pub identity_timeout_ms: u64,
+ /// Number of gRPC channels to open to each leader pod (leader mode only)
+ #[envconfig(default = "4")]
+ pub leader_channels: usize,
+
/// Timeout for backend requests in milliseconds
#[envconfig(default = "5000")]
pub backend_timeout_ms: u64,
diff --git a/rust/personhog-router/src/main.rs b/rust/personhog-router/src/main.rs
index fff644dbfcf2..f195f8f8c571 100644
--- a/rust/personhog-router/src/main.rs
+++ b/rust/personhog-router/src/main.rs
@@ -296,6 +296,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
LeaderBackendConfig {
num_partitions,
timeout: config.backend_timeout(),
+ num_channels: config.leader_channels,
http2_windows: config.backend_http2_windows(),
},
StashTable::with_bounds(
diff --git a/rust/personhog-router/tests/common/mod.rs b/rust/personhog-router/tests/common/mod.rs
index 183b957034d8..0051da715a71 100644
--- a/rust/personhog-router/tests/common/mod.rs
+++ b/rust/personhog-router/tests/common/mod.rs
@@ -969,6 +969,7 @@ fn make_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Arc<Lead
LeaderBackendConfig {
num_partitions,
timeout: Duration::from_secs(5),
+ num_channels: 1,
http2_windows: Http2Windows::default(),
},
StashTable::with_bounds(usize::MAX, usize::MAX),
@@ -1002,6 +1003,7 @@ fn make_dying_leader_backend(leader_addr: SocketAddr, num_partitions: u32) -> Ar
LeaderBackendConfig {
num_partitions,
timeout: Duration::from_millis(200),
+ num_channels: 1,
http2_windows: Http2Windows::default(),
},
StashTable::with_bounds(usize::MAX, usize::MAX),
diff --git a/rust/personhog-router/tests/h2_window_wiring.rs b/rust/personhog-router/tests/h2_window_wiring.rs
index 9bce872146fe..cadd243e5cf8 100644
--- a/rust/personhog-router/tests/h2_window_wiring.rs
+++ b/rust/personhog-router/tests/h2_window_wiring.rs
@@ -167,6 +167,7 @@ async fn leader_channel(addr: SocketAddr, http2_windows: Http2Windows) -> Channe
LeaderBackendConfig {
num_partitions: 1,
timeout: Duration::from_secs(5),
+ num_channels: 1,
http2_windows,
},
StashTable::with_bounds(usize::MAX, usize::MAX),
diff --git a/rust/personhog-router/tests/stash_integration.rs b/rust/personhog-router/tests/stash_integration.rs
index 614e49c00be5..058e4bfaa5d4 100644
--- a/rust/personhog-router/tests/stash_integration.rs
+++ b/rust/personhog-router/tests/stash_integration.rs
@@ -66,6 +66,7 @@ async fn make_backend(leader_addr: std::net::SocketAddr, stash: StashTable) -> A
LeaderBackendConfig {
num_partitions: NUM_PARTITIONS,
timeout: Duration::from_secs(5),
+ num_channels: 1,
http2_windows: Http2Windows::default(),
},
stash,