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.

chore(posthog): add personhog retries (#62485)

Zach Browna10d13f26f9b
diff --git a/posthog/personhog_client/client.py b/posthog/personhog_client/client.py
index bb4072f960cc..c5c0fae53bd6 100644
--- a/posthog/personhog_client/client.py
+++ b/posthog/personhog_client/client.py
@@ -10,7 +10,12 @@ import grpc
import structlog
from prometheus_client import Counter, Enum, Histogram
-from posthog.personhog_client.interceptor import ClientNameInterceptor, ConsistencyHeaderInterceptor, MetricsInterceptor
+from posthog.personhog_client.interceptor import (
+ ClientNameInterceptor,
+ ConsistencyHeaderInterceptor,
+ MetricsInterceptor,
+ RetryInterceptor,
+)
from posthog.personhog_client.proto import (
CheckCohortMembershipRequest,
CohortMembershipResponse,
@@ -155,6 +160,9 @@ class PersonHogClient:
max_send_message_length: int = 4 * 1024 * 1024,
max_recv_message_length: int = 128 * 1024 * 1024,
client_idle_timeout_ms: int = 0,
+ max_retries: int = 1,
+ initial_backoff_ms: int = 50,
+ max_backoff_ms: int = 1000,
):
options = [
("grpc.keepalive_time_ms", keepalive_time_ms),
@@ -173,6 +181,12 @@ class PersonHogClient:
channel,
ClientNameInterceptor(client_name),
ConsistencyHeaderInterceptor(),
+ RetryInterceptor(
+ client_name,
+ max_retries=max_retries,
+ initial_backoff_ms=initial_backoff_ms,
+ max_backoff_ms=max_backoff_ms,
+ ),
MetricsInterceptor(client_name),
)
self._state_monitor = _ChannelStateMonitor(channel, client_name)
@@ -348,6 +362,9 @@ def get_personhog_client() -> Optional[PersonHogClient]:
max_send_message_length=getattr(settings, "PERSONHOG_MAX_SEND_MESSAGE_LENGTH", 4 * 1024 * 1024),
max_recv_message_length=getattr(settings, "PERSONHOG_MAX_RECV_MESSAGE_LENGTH", 128 * 1024 * 1024),
client_idle_timeout_ms=getattr(settings, "PERSONHOG_CLIENT_IDLE_TIMEOUT_MS", 0),
+ max_retries=getattr(settings, "PERSONHOG_MAX_RETRIES", 1),
+ initial_backoff_ms=getattr(settings, "PERSONHOG_INITIAL_BACKOFF_MS", 50),
+ max_backoff_ms=getattr(settings, "PERSONHOG_MAX_BACKOFF_MS", 1000),
)
logger.info("personhog_client_initialized", addr=addr, timeout_ms=timeout_ms)
diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.py
index f87453145695..d9fa7f7d3719 100644
--- a/posthog/personhog_client/interceptor.py
+++ b/posthog/personhog_client/interceptor.py
@@ -1,16 +1,24 @@
from __future__ import annotations
import time
+import random
from collections import namedtuple
from collections.abc import Sequence
from typing import Any
import grpc
+import structlog
from prometheus_client import Counter, Histogram
-from posthog.personhog_client.metrics import PERSONHOG_ERRORS_TOTAL
+from posthog.personhog_client.metrics import (
+ PERSONHOG_ERRORS_TOTAL,
+ PERSONHOG_RETRIES_TOTAL,
+ PERSONHOG_TERMINAL_ERRORS_TOTAL,
+)
from posthog.personhog_client.proto import CONSISTENCY_LEVEL_STRONG
+logger = structlog.get_logger(__name__)
+
_ClientCallDetails = namedtuple(
"_ClientCallDetails",
["method", "timeout", "metadata", "credentials", "wait_for_ready", "compression"],
@@ -135,3 +143,71 @@ class MetricsInterceptor(grpc.UnaryUnaryClientInterceptor):
PERSONHOG_DJANGO_REQUEST_DURATION.labels(method=method, client_name=self._client_name).observe(
time.monotonic() - start
)
+
+
+_RETRYABLE_CODES = frozenset(
+ {
+ grpc.StatusCode.UNAVAILABLE,
+ grpc.StatusCode.DEADLINE_EXCEEDED,
+ grpc.StatusCode.ABORTED,
+ }
+)
+
+
+class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
+ """Retries transient gRPC errors with jittered backoff.
+
+ Covers three failure modes:
+ - UNAVAILABLE: client-to-router connection failure
+ - ABORTED: HTTP/2 stream reset during router deploys
+ - DEADLINE_EXCEEDED: transient timeout (event loop saturation, brief backend slowness)
+
+ Sits outside MetricsInterceptor so each attempt gets its own per-call metrics.
+ """
+
+ def __init__(
+ self, client_name: str, max_retries: int = 1, initial_backoff_ms: int = 50, max_backoff_ms: int = 1000
+ ) -> None:
+ self._client_name = client_name
+ self._max_retries = max_retries
+ self._initial_backoff_ms = initial_backoff_ms
+ self._max_backoff_ms = max_backoff_ms
+
+ def intercept_unary_unary(
+ self,
+ continuation: Any,
+ client_call_details: grpc.ClientCallDetails,
+ request: Any,
+ ) -> Any:
+ method = _method_name(client_call_details)
+ attempt = 0
+ delay_ms = self._initial_backoff_ms
+
+ while True:
+ try:
+ return continuation(client_call_details, request)
+ except grpc.RpcError as exc:
+ code = exc.code()
+ error_type = _grpc_error_type(code) if code else "Unknown"
+ retryable = code in _RETRYABLE_CODES if code else False
+
+ if not retryable or attempt == self._max_retries:
+ PERSONHOG_TERMINAL_ERRORS_TOTAL.labels(
+ method=method, client=self._client_name, error_type=error_type
+ ).inc()
+ raise
+
+ PERSONHOG_RETRIES_TOTAL.labels(method=method, client=self._client_name, error_type=error_type).inc()
+
+ logger.warning(
+ "personhog_grpc_retry",
+ method=method,
+ attempt=attempt + 1,
+ max_retries=self._max_retries,
+ error_type=error_type,
+ )
+
+ base = delay_ms / 2
+ time.sleep((base + random.uniform(0, base)) / 1000)
+ delay_ms = min(delay_ms * 2, self._max_backoff_ms)
+ attempt += 1
diff --git a/posthog/personhog_client/metrics.py b/posthog/personhog_client/metrics.py
index 4f10245a7e5d..016a3f34d84e 100644
--- a/posthog/personhog_client/metrics.py
+++ b/posthog/personhog_client/metrics.py
@@ -32,3 +32,15 @@ PERSONHOG_ERRORS_TOTAL = Counter(
"Total PersonHog gRPC errors — every failed gRPC attempt",
labelnames=["method", "client", "error_type"],
)
+
+PERSONHOG_RETRIES_TOTAL = Counter(
+ "personhog_retries_total",
+ "Total PersonHog gRPC retries before success or exhaustion",
+ labelnames=["method", "client", "error_type"],
+)
+
+PERSONHOG_TERMINAL_ERRORS_TOTAL = Counter(
+ "personhog_terminal_errors_total",
+ "PersonHog gRPC errors after retry exhaustion — the request was not fulfilled",
+ labelnames=["method", "client", "error_type"],
+)
diff --git a/posthog/personhog_client/test_retry_interceptor.py b/posthog/personhog_client/test_retry_interceptor.py
new file mode 100644
index 000000000000..b8d9577cdad2
--- /dev/null
+++ b/posthog/personhog_client/test_retry_interceptor.py
@@ -0,0 +1,182 @@
+from __future__ import annotations
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import grpc
+from parameterized import parameterized
+
+from posthog.personhog_client.interceptor import RetryInterceptor, _MutableClientCallDetails
+
+
+def _make_call_details(
+ method: str = "/personhog.service.v1.PersonHogService/GetPerson",
+) -> grpc.ClientCallDetails:
+ return _MutableClientCallDetails(
+ method=method,
+ timeout=5.0,
+ metadata=None,
+ credentials=None,
+ wait_for_ready=None,
+ compression=None,
+ )
+
+
+def _make_rpc_error(status_code: grpc.StatusCode) -> grpc.RpcError:
+ error = grpc.RpcError()
+ error.code = MagicMock(return_value=status_code)
+ return error
+
+
+def _make_transient_then_ok(fail_count: int, status_code: grpc.StatusCode):
+ """Returns a continuation that fails fail_count times then succeeds."""
+ calls: list[int] = []
+
+ def continuation(details, request):
+ calls.append(1)
+ if len(calls) <= fail_count:
+ raise _make_rpc_error(status_code)
+ return "ok"
+
+ return continuation, calls
+
+
+def _make_always_failing(status_code: grpc.StatusCode):
+ """Returns a continuation that always raises the given status code."""
+ calls: list[int] = []
+
+ def continuation(details, request):
+ calls.append(1)
+ raise _make_rpc_error(status_code)
+
+ return continuation, calls
+
+
+class TestRetryInterceptorBehavior:
+ def test_returns_on_first_success(self):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+
+ result = interceptor.intercept_unary_unary(lambda d, r: "ok", details, request=b"")
+
+ assert result == "ok"
+
+ @parameterized.expand(
+ [
+ ("unavailable", grpc.StatusCode.UNAVAILABLE),
+ ("deadline_exceeded", grpc.StatusCode.DEADLINE_EXCEEDED),
+ ("aborted", grpc.StatusCode.ABORTED),
+ ]
+ )
+ @patch("posthog.personhog_client.interceptor.time.sleep")
+ def test_retries_transient_error_then_succeeds(self, _name: str, status_code: grpc.StatusCode, mock_sleep):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, calls = _make_transient_then_ok(1, status_code)
+
+ result = interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ assert result == "ok"
+ assert len(calls) == 2
+ assert mock_sleep.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("not_found", grpc.StatusCode.NOT_FOUND),
+ ("invalid_argument", grpc.StatusCode.INVALID_ARGUMENT),
+ ("permission_denied", grpc.StatusCode.PERMISSION_DENIED),
+ ("unauthenticated", grpc.StatusCode.UNAUTHENTICATED),
+ ("failed_precondition", grpc.StatusCode.FAILED_PRECONDITION),
+ ("internal", grpc.StatusCode.INTERNAL),
+ ("resource_exhausted", grpc.StatusCode.RESOURCE_EXHAUSTED),
+ ("unknown", grpc.StatusCode.UNKNOWN),
+ ]
+ )
+ def test_does_not_retry_non_retryable_error(self, _name: str, status_code: grpc.StatusCode):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, calls = _make_always_failing(status_code)
+
+ with pytest.raises(grpc.RpcError):
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ assert len(calls) == 1
+
+ @patch("posthog.personhog_client.interceptor.time.sleep")
+ def test_exhausts_retries_on_persistent_transient_error(self, mock_sleep):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, calls = _make_always_failing(grpc.StatusCode.UNAVAILABLE)
+
+ with pytest.raises(grpc.RpcError):
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ # 1 initial + 1 retry = 2 total attempts
+ assert len(calls) == 2
+ assert mock_sleep.call_count == 1
+
+ def test_no_retries_when_max_retries_is_zero(self):
+ interceptor = RetryInterceptor("test-client", max_retries=0, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, calls = _make_always_failing(grpc.StatusCode.UNAVAILABLE)
+
+ with pytest.raises(grpc.RpcError):
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ assert len(calls) == 1
+
+
+class TestRetryInterceptorMetrics:
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_RETRIES_TOTAL")
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_TERMINAL_ERRORS_TOTAL")
+ @patch("posthog.personhog_client.interceptor.time.sleep")
+ def test_emits_retry_metrics_per_attempt(self, mock_sleep, mock_terminal, mock_retries):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, _ = _make_transient_then_ok(1, grpc.StatusCode.UNAVAILABLE)
+
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ assert mock_retries.labels.return_value.inc.call_count == 1
+ mock_retries.labels.assert_called_with(method="GetPerson", client="test-client", error_type="Unavailable")
+ mock_terminal.labels.return_value.inc.assert_not_called()
+
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_RETRIES_TOTAL")
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_TERMINAL_ERRORS_TOTAL")
+ @patch("posthog.personhog_client.interceptor.time.sleep")
+ def test_emits_terminal_metric_on_exhaustion(self, mock_sleep, mock_terminal, mock_retries):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, _ = _make_always_failing(grpc.StatusCode.UNAVAILABLE)
+
+ with pytest.raises(grpc.RpcError):
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ mock_terminal.labels.assert_called_with(method="GetPerson", client="test-client", error_type="Unavailable")
+ mock_terminal.labels.return_value.inc.assert_called_once()
+ assert mock_retries.labels.return_value.inc.call_count == 1
+
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_RETRIES_TOTAL")
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_TERMINAL_ERRORS_TOTAL")
+ def test_emits_terminal_metric_on_non_retryable_error(self, mock_terminal, mock_retries):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, _ = _make_always_failing(grpc.StatusCode.NOT_FOUND)
+
+ with pytest.raises(grpc.RpcError):
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ mock_terminal.labels.assert_called_with(method="GetPerson", client="test-client", error_type="NotFound")
+ mock_terminal.labels.return_value.inc.assert_called_once()
+ mock_retries.labels.return_value.inc.assert_not_called()
+
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_RETRIES_TOTAL")
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_TERMINAL_ERRORS_TOTAL")
+ def test_no_retry_or_terminal_metrics_on_success(self, mock_terminal, mock_retries):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+
+ interceptor.intercept_unary_unary(lambda d, r: "ok", details, request=b"")
+
+ mock_retries.labels.return_value.inc.assert_not_called()
+ mock_terminal.labels.return_value.inc.assert_not_called()
diff --git a/posthog/settings/personhog.py b/posthog/settings/personhog.py
index d01d18e71d14..16b1076611e6 100644
--- a/posthog/settings/personhog.py
+++ b/posthog/settings/personhog.py
@@ -15,6 +15,11 @@ PERSONHOG_MAX_SEND_MESSAGE_LENGTH = get_from_env("PERSONHOG_MAX_SEND_MESSAGE_LEN
PERSONHOG_MAX_RECV_MESSAGE_LENGTH = get_from_env("PERSONHOG_MAX_RECV_MESSAGE_LENGTH", 128 * 1024 * 1024, type_cast=int)
PERSONHOG_CLIENT_IDLE_TIMEOUT_MS = get_from_env("PERSONHOG_CLIENT_IDLE_TIMEOUT_MS", 0, type_cast=int)
+# Retry settings for transient gRPC errors (before falling back to ORM)
+PERSONHOG_MAX_RETRIES = get_from_env("PERSONHOG_MAX_RETRIES", 1, type_cast=int)
+PERSONHOG_INITIAL_BACKOFF_MS = get_from_env("PERSONHOG_INITIAL_BACKOFF_MS", 50, type_cast=int)
+PERSONHOG_MAX_BACKOFF_MS = get_from_env("PERSONHOG_MAX_BACKOFF_MS", 1000, type_cast=int)
+
# Server enforces a hard limit of 250 IDs per batch lookup request for person records.
_PERSONHOG_MAX_BATCH_SIZE = 250
PERSONHOG_BATCH_SIZE: int = max(