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.

fix(personhog): retry identity's leader calls through the router (#117178)

Zach Brown24d9f1008d27
diff --git a/rust/personhog-common/src/client.rs b/rust/personhog-common/src/client.rs
index d5bd9e344c14..8ba04e1b7a04 100644
--- a/rust/personhog-common/src/client.rs
+++ b/rust/personhog-common/src/client.rs
@@ -33,6 +33,18 @@ pub const READ_CONSISTENCY_HEADER: &str = "x-read-consistency";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+const RETRY_BACKOFF: Duration = Duration::from_millis(100);
+
+pub const ROUTER_CLIENT_RETRIES_TOTAL: &str = "personhog_router_client_retries_total";
+
+/// The channel's pod went away, the request timed out, or the router ran out of routes.
+fn is_transport_failure(status: &Status) -> bool {
+ matches!(
+ status.code(),
+ tonic::Code::Unavailable | tonic::Code::Unknown | tonic::Code::Cancelled
+ )
+}
+
pub const ROUTER_CLIENT_CALLS_TOTAL: &str = "personhog_router_client_calls_total";
pub const ROUTER_CLIENT_CALL_DURATION_MS: &str = "personhog_router_client_call_duration_ms";
@@ -54,6 +66,7 @@ pub struct RouterClient {
/// than every clone restarting at the first channel.
next: Arc<AtomicUsize>,
request_timeout: Duration,
+ attempts: u32,
client_name: Option<&'static str>,
}
@@ -104,6 +117,7 @@ impl RouterClient {
clients,
next: Arc::new(AtomicUsize::new(0)),
request_timeout,
+ attempts: 1,
client_name: None,
})
}
@@ -116,6 +130,13 @@ impl RouterClient {
self
}
+ /// Retries a strong read or property write on a transport failure, each attempt on the next
+ /// channel. Both are safe to repeat: the leader answers an applied write with no change.
+ pub fn with_attempts(mut self, attempts: u32) -> Self {
+ self.attempts = attempts.max(1);
+ self
+ }
+
fn request<T>(&self, message: T) -> Request<T> {
let mut request = Request::new(message);
request.set_timeout(self.request_timeout);
@@ -152,17 +173,41 @@ impl RouterClient {
self.clients[idx].clone()
}
+ /// Up to `attempts` calls, each timed, stopping at the first answer that is not a transport failure.
+ async fn retried<T, F, Fut>(
+ attempts: u32,
+ method: &'static str,
+ mut call: F,
+ ) -> Result<T, Status>
+ where
+ F: FnMut() -> Fut,
+ Fut: Future<Output = Result<Response<T>, Status>>,
+ {
+ let mut attempt = 1;
+ loop {
+ match Self::timed(method, call()).await {
+ Err(status) if attempt < attempts && is_transport_failure(&status) => {
+ counter!(ROUTER_CLIENT_RETRIES_TOTAL, "method" => method, "outcome" => code_as_str(status.code()))
+ .increment(1);
+ tokio::time::sleep(RETRY_BACKOFF * attempt).await;
+ attempt += 1;
+ }
+ result => return result,
+ }
+ }
+ }
+
/// Leader-routed property write. The routing headers are stamped from
/// the request's own team_id/person_id.
pub async fn update_person_properties(
&self,
request: UpdatePersonPropertiesRequest,
) -> Result<UpdatePersonPropertiesResponse, Status> {
- let request = self.build_update_request(request);
- Self::timed(
- "UpdatePersonProperties",
- self.client().update_person_properties(request),
- )
+ Self::retried(self.attempts, "UpdatePersonProperties", || {
+ let request = self.build_update_request(request.clone());
+ let mut client = self.client();
+ async move { client.update_person_properties(request).await }
+ })
.await
}
@@ -175,10 +220,13 @@ impl RouterClient {
person_id: i64,
consistency: ConsistencyLevel,
) -> Result<Option<Person>, Status> {
- let request = self.build_get_person_request(team_id, person_id, consistency);
- Self::timed("GetPerson", self.client().get_person(request))
- .await
- .map(|response| response.person)
+ Self::retried(self.attempts, "GetPerson", || {
+ let request = self.build_get_person_request(team_id, person_id, consistency);
+ let mut client = self.client();
+ async move { client.get_person(request).await }
+ })
+ .await
+ .map(|response| response.person)
}
/// Leader-routed lifecycle fence (saga runner only): freeze the person
@@ -405,4 +453,86 @@ mod tests {
assert!(metadata.get(READ_CONSISTENCY_HEADER).is_none());
}
}
+
+ /// Answers the scripted statuses in order, then succeeds; counts calls.
+ fn scripted(
+ failures: Vec<tonic::Code>,
+ calls: Arc<AtomicUsize>,
+ ) -> impl FnMut() -> std::future::Ready<Result<Response<u8>, Status>> {
+ let mut failures = failures.into_iter();
+ move || {
+ calls.fetch_add(1, Ordering::Relaxed);
+ std::future::ready(match failures.next() {
+ Some(code) => Err(Status::new(code, "scripted")),
+ None => Ok(Response::new(1)),
+ })
+ }
+ }
+
+ #[rstest]
+ #[case::unavailable(2, vec![tonic::Code::Unavailable])]
+ #[case::unknown(2, vec![tonic::Code::Unknown])]
+ #[case::cancelled(2, vec![tonic::Code::Cancelled])]
+ #[case::two_failures_under_three_attempts(3, vec![tonic::Code::Unavailable, tonic::Code::Cancelled])]
+ #[tokio::test]
+ async fn transport_failures_are_retried_up_to_the_attempt_count(
+ #[case] attempts: u32,
+ #[case] failures: Vec<tonic::Code>,
+ ) {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let expected_calls = failures.len() + 1;
+
+ let result =
+ RouterClient::retried(attempts, "test", scripted(failures, calls.clone())).await;
+
+ assert_eq!(result.unwrap(), 1);
+ assert_eq!(calls.load(Ordering::Relaxed), expected_calls);
+ }
+
+ #[rstest]
+ #[case::not_found(tonic::Code::NotFound)]
+ #[case::failed_precondition(tonic::Code::FailedPrecondition)]
+ #[case::invalid_argument(tonic::Code::InvalidArgument)]
+ #[tokio::test]
+ async fn an_answer_about_the_request_is_not_retried(#[case] code: tonic::Code) {
+ let calls = Arc::new(AtomicUsize::new(0));
+
+ let result = RouterClient::retried(2, "test", scripted(vec![code], calls.clone())).await;
+
+ assert_eq!(result.unwrap_err().code(), code);
+ assert_eq!(calls.load(Ordering::Relaxed), 1);
+ }
+
+ #[tokio::test]
+ async fn a_single_attempt_fails_on_the_first_transport_failure() {
+ let calls = Arc::new(AtomicUsize::new(0));
+
+ let result = RouterClient::retried(
+ client().attempts,
+ "test",
+ scripted(vec![tonic::Code::Unavailable], calls.clone()),
+ )
+ .await;
+
+ assert_eq!(result.unwrap_err().code(), tonic::Code::Unavailable);
+ assert_eq!(calls.load(Ordering::Relaxed), 1);
+ }
+
+ #[tokio::test]
+ async fn exhausted_attempts_return_the_last_failure() {
+ let calls = Arc::new(AtomicUsize::new(0));
+
+ let result = RouterClient::retried(
+ 2,
+ "test",
+ scripted(
+ vec![tonic::Code::Unavailable, tonic::Code::Cancelled],
+ calls.clone(),
+ ),
+ )
+ .await;
+
+ assert_eq!(result.unwrap_err().code(), tonic::Code::Cancelled);
+ assert_eq!(calls.load(Ordering::Relaxed), 2);
+ }
}
diff --git a/rust/personhog-identity/src/config.rs b/rust/personhog-identity/src/config.rs
index 9102ad62270c..831447919c53 100644
--- a/rust/personhog-identity/src/config.rs
+++ b/rust/personhog-identity/src/config.rs
@@ -125,10 +125,14 @@ pub struct Config {
#[envconfig(default = "0")]
pub router_initial_connection_window_bytes: WindowSize,
- /// Per-call timeout for leader-routed property writes (ms).
+ /// Per-attempt timeout for leader-routed property writes and strong reads (ms).
#[envconfig(default = "5000")]
pub leader_request_timeout_ms: u64,
+ /// Attempts per leader-routed write or strong read, each under `leader_request_timeout_ms`.
+ #[envconfig(default = "2")]
+ pub leader_request_attempts: u32,
+
/// etcd endpoints, comma separated. The delete saga groups its fence
/// calls by leader partition, and the partition count lives in etcd.
#[envconfig(default = "http://localhost:2379")]
diff --git a/rust/personhog-identity/src/main.rs b/rust/personhog-identity/src/main.rs
index 86d1bcfaa1a6..279f86f21bc9 100644
--- a/rust/personhog-identity/src/main.rs
+++ b/rust/personhog-identity/src/main.rs
@@ -273,7 +273,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
config.router_http2_windows(),
)
.expect("Invalid router URL")
- .with_client_name("personhog-identity"),
+ .with_client_name("personhog-identity")
+ .with_attempts(config.leader_request_attempts),
);
// Both sagas' leader surface, reached through the router like the
// property writes.