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(personhog): pool router connections in the shared client (#82816)

Zach Browna426217ab440
diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rs
index 09637ef0ec2b..a2918a1852ad 100644
--- a/rust/personhog-common/src/client.rs
+++ b/rust/personhog-common/src/client.rs
@@ -5,6 +5,8 @@
//! `x-team-id`/`x-person-id` on property writes and strong reads. This
//! client owns that contract so callers cannot get it wrong.
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
use std::time::Duration;
use tonic::transport::{Channel, Endpoint};
@@ -24,29 +26,70 @@ pub const READ_CONSISTENCY_HEADER: &str = "x-read-consistency";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+/// Channels opened per router URL when the caller does not choose. One is
+/// correct only for low-rate callers; see `with_channels`.
+pub const DEFAULT_ROUTER_CHANNELS: usize = 1;
+
#[derive(Clone)]
pub struct RouterClient {
- inner: PersonHogServiceClient<Channel>,
+ /// One tonic channel is one TCP connection, and a Kubernetes Service
+ /// pins a connection to a single backend pod for its lifetime. A
+ /// single-channel client therefore sends everything this process
+ /// produces to one router pod, however many pods exist. Holding
+ /// several channels spreads the load across as many pods, and gives
+ /// each connection its own HTTP/2 stream budget and flow-control
+ /// windows.
+ clients: Vec<PersonHogServiceClient<Channel>>,
+ /// Shared across clones so round-robin continues across them rather
+ /// than every clone restarting at the first channel.
+ next: Arc<AtomicUsize>,
request_timeout: Duration,
}
impl RouterClient {
- /// Connect lazily to the router; the first RPC establishes the
- /// connection.
+ /// Connect lazily to the router over a single channel; the first RPC
+ /// establishes the connection.
pub fn new(
router_url: &str,
request_timeout: Duration,
) -> Result<Self, tonic::transport::Error> {
- let channel = Endpoint::from_shared(router_url.to_string())?
- .connect_timeout(CONNECT_TIMEOUT)
- .tcp_nodelay(true)
- .connect_lazy();
+ Self::with_channels(router_url, request_timeout, DEFAULT_ROUTER_CHANNELS)
+ }
+
+ /// Connect lazily over `channels` connections, selected round-robin
+ /// per request. Callers driving meaningful request rates want more
+ /// than one: a single connection caps them at one router pod's
+ /// capacity no matter how many pods are running. A count below one is
+ /// treated as one.
+ pub fn with_channels(
+ router_url: &str,
+ request_timeout: Duration,
+ channels: usize,
+ ) -> Result<Self, tonic::transport::Error> {
+ let clients = (0..channels.max(1))
+ .map(|_| {
+ let channel = Endpoint::from_shared(router_url.to_string())?
+ .connect_timeout(CONNECT_TIMEOUT)
+ .tcp_nodelay(true)
+ .connect_lazy();
+ Ok(PersonHogServiceClient::new(channel))
+ })
+ .collect::<Result<Vec<_>, tonic::transport::Error>>()?;
Ok(Self {
- inner: PersonHogServiceClient::new(channel),
+ clients,
+ next: Arc::new(AtomicUsize::new(0)),
request_timeout,
})
}
+ /// The next channel in round-robin order. Selection is load-oblivious:
+ /// a stalled connection still takes its share, which is acceptable
+ /// because every channel targets the same interchangeable pod set.
+ fn client(&self) -> PersonHogServiceClient<Channel> {
+ let idx = self.next.fetch_add(1, Ordering::Relaxed) % self.clients.len();
+ self.clients[idx].clone()
+ }
+
/// Leader-routed property write. The routing headers are stamped from
/// the request's own team_id/person_id.
pub async fn update_person_properties(
@@ -54,8 +97,7 @@ impl RouterClient {
request: UpdatePersonPropertiesRequest,
) -> Result<UpdatePersonPropertiesResponse, Status> {
let request = self.build_update_request(request);
- self.inner
- .clone()
+ self.client()
.update_person_properties(request)
.await
.map(|response| response.into_inner())
@@ -71,8 +113,7 @@ impl RouterClient {
consistency: ConsistencyLevel,
) -> Result<Option<Person>, Status> {
let request = self.build_get_person_request(team_id, person_id, consistency);
- self.inner
- .clone()
+ self.client()
.get_person(request)
.await
.map(|response| response.into_inner().person)
@@ -88,8 +129,7 @@ impl RouterClient {
let mut request = Request::new(request);
request.set_timeout(self.request_timeout);
stamp_person_routing_headers(&mut request, team_id, person_id);
- self.inner
- .clone()
+ self.client()
.fence_person(request)
.await
.map(|response| response.into_inner())
@@ -105,8 +145,7 @@ impl RouterClient {
let mut request = Request::new(request);
request.set_timeout(self.request_timeout);
stamp_person_routing_headers(&mut request, team_id, person_id);
- self.inner
- .clone()
+ self.client()
.release_fence(request)
.await
.map(|response| response.into_inner())
@@ -122,8 +161,7 @@ impl RouterClient {
let mut request = Request::new(request);
request.set_timeout(self.request_timeout);
stamp_person_routing_headers(&mut request, team_id, person_id);
- self.inner
- .clone()
+ self.client()
.fold_person_document(request)
.await
.map(|response| response.into_inner())
@@ -200,6 +238,31 @@ mod tests {
.expect("lazy client construction cannot fail on a valid url")
}
+ /// A single connection is pinned to one router pod by the Service, so
+ /// a pooled client must actually hand out different channels — and
+ /// keep doing so across clones, which is how callers hold it.
+ #[tokio::test]
+ async fn requests_round_robin_across_the_pool_including_clones() {
+ let client = RouterClient::with_channels("http://127.0.0.1:1", Duration::from_secs(1), 4)
+ .expect("lazy client construction cannot fail on a valid url");
+
+ let first = client.next.load(Ordering::Relaxed);
+ for _ in 0..4 {
+ drop(client.clone().client());
+ }
+ assert_eq!(client.next.load(Ordering::Relaxed), first + 4);
+ }
+
+ /// Zero would panic on the modulo; callers reading it from config get
+ /// the single-channel behavior instead.
+ #[tokio::test]
+ async fn a_channel_count_below_one_still_yields_a_usable_client() {
+ let client = RouterClient::with_channels("http://127.0.0.1:1", Duration::from_secs(1), 0)
+ .expect("lazy client construction cannot fail on a valid url");
+ assert_eq!(client.clients.len(), 1);
+ drop(client.client());
+ }
+
// Channel construction (even lazy) needs a Tokio reactor, hence async tests.
#[tokio::test]
async fn update_request_carries_the_routing_headers() {
diff --git a/rust/personhog-test-harness/src/cli.rs b/rust/personhog-test-harness/src/cli.rs
index 16514973ee7e..ba94a0846762 100644
--- a/rust/personhog-test-harness/src/cli.rs
+++ b/rust/personhog-test-harness/src/cli.rs
@@ -9,6 +9,11 @@ pub const DEFAULT_PERSONS_DB_URL: &str =
/// The dev-stack leader-mode router (bin/mprocs.yaml `personhog-router-leader`).
pub const DEV_STACK_ROUTER_URL: &str = "http://127.0.0.1:50054";
+/// Connections a load-driving scenario opens to the router by default.
+/// Sized so a deployed instance spreads over a meaningful slice of a
+/// router fleet while staying trivial against a single local router.
+pub const DEFAULT_ROUTER_CHANNELS: usize = 8;
+
/// Keys a traffic lane holds a person's document at. The changelog carries
/// the whole document per update, so this multiplies the bed's byte rate.
pub const DEFAULT_KEYS_PER_PERSON: u64 = 64;
@@ -79,6 +84,10 @@ pub struct BlastArgs {
#[arg(long, default_value = DEV_STACK_ROUTER_URL)]
pub router_url: String,
+ /// Connections to open to the router; see TrafficArgs::router_channels.
+ #[arg(long, default_value_t = DEFAULT_ROUTER_CHANNELS)]
+ pub router_channels: usize,
+
#[arg(long)]
pub team_id: i64,
@@ -351,6 +360,13 @@ pub struct TrafficArgs {
#[arg(long, env = "TRAFFIC_IDENTITY_URL")]
pub identity_url: String,
+ /// Connections this instance opens to the router. A Kubernetes Service
+ /// pins each connection to one router pod, so a single connection
+ /// confines an instance's whole load to one pod and measures that
+ /// pod's ceiling rather than the fleet's.
+ #[arg(long, env = "TRAFFIC_ROUTER_CHANNELS", default_value_t = DEFAULT_ROUTER_CHANNELS)]
+ pub router_channels: usize,
+
/// Master toggle. When false the process starts fully (guard, metrics,
/// liveness) but idles instead of driving traffic — so a deployed-but-
/// disabled harness is observably "off on purpose" rather than absent.
diff --git a/rust/personhog-test-harness/src/client.rs b/rust/personhog-test-harness/src/client.rs
index c5cbb83e8818..286dc45f8de4 100644
--- a/rust/personhog-test-harness/src/client.rs
+++ b/rust/personhog-test-harness/src/client.rs
@@ -31,7 +31,16 @@ pub struct HarnessClient {
impl HarnessClient {
pub async fn connect(url: &str) -> Result<Self> {
- let inner = RouterClient::new(url, REQUEST_TIMEOUT).context("invalid router URL")?;
+ Self::connect_with_channels(url, 1).await
+ }
+
+ /// Connect over `channels` router connections, selected round-robin.
+ /// Load-driving scenarios pass more than one so an instance spreads
+ /// across router pods instead of pinning to whichever pod its single
+ /// connection landed on.
+ pub async fn connect_with_channels(url: &str, channels: usize) -> Result<Self> {
+ let inner = RouterClient::with_channels(url, REQUEST_TIMEOUT, channels)
+ .context("invalid router URL")?;
Ok(Self { inner })
}
diff --git a/rust/personhog-test-harness/src/scenarios/blast.rs b/rust/personhog-test-harness/src/scenarios/blast.rs
index 32a0874b722a..40d5fa9f96da 100644
--- a/rust/personhog-test-harness/src/scenarios/blast.rs
+++ b/rust/personhog-test-harness/src/scenarios/blast.rs
@@ -18,7 +18,8 @@ use crate::stats::StatsCollector;
use crate::traffic_metrics;
pub async fn run(args: BlastArgs) -> Result<()> {
- let client = HarnessClient::connect(&args.router_url).await?;
+ let client =
+ HarnessClient::connect_with_channels(&args.router_url, args.router_channels).await?;
let person_ids = Arc::new(args.person_ids.clone());
println!(
diff --git a/rust/personhog-test-harness/src/scenarios/traffic.rs b/rust/personhog-test-harness/src/scenarios/traffic.rs
index c214e700ef44..bc8efeb057c0 100644
--- a/rust/personhog-test-harness/src/scenarios/traffic.rs
+++ b/rust/personhog-test-harness/src/scenarios/traffic.rs
@@ -141,7 +141,8 @@ pub async fn run(args: TrafficArgs) -> Result<()> {
shutdown_signal().await;
return Ok(());
}
- let client = HarnessClient::connect(&args.router_url).await?;
+ let client =
+ HarnessClient::connect_with_channels(&args.router_url, args.router_channels).await?;
let identity = IdentityClient::connect(&args.identity_url).await?;
let lifecycle = LifecycleClient::connect(&args.identity_url).await?;
let pool = PgPool::connect(&args.persons_db_url)
@@ -799,7 +800,7 @@ async fn shutdown_signal() {
#[cfg(test)]
mod tests {
use super::*;
- use crate::cli::DEFAULT_KEYS_PER_PERSON;
+ use crate::cli::{DEFAULT_KEYS_PER_PERSON, DEFAULT_ROUTER_CHANNELS};
/// Needs the CI gate's etcd; run explicitly with `--ignored`.
#[tokio::test]
@@ -844,6 +845,7 @@ mod tests {
chaos_etcd_namespace: None,
router_url: "http://localhost:1".to_string(),
identity_url: "http://localhost:2".to_string(),
+ router_channels: DEFAULT_ROUTER_CHANNELS,
enabled: true,
team_ids: vec![900_101],
hostile_team_id: 900_102,