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(personhog): unify client error metrics (#62244)

Zach Brownae70b4ccf5fa
diff --git a/nodejs/src/ingestion/personhog/grpc-retry.test.ts b/nodejs/src/ingestion/personhog/grpc-retry.test.ts
index cd39d9bd044e..401acc223b65 100644
--- a/nodejs/src/ingestion/personhog/grpc-retry.test.ts
+++ b/nodejs/src/ingestion/personhog/grpc-retry.test.ts
@@ -6,19 +6,23 @@ jest.mock('../../utils/logger')
describe('withRetry', () => {
it('returns the result on first success', async () => {
- const result = await withRetry('test', () => Promise.resolve('ok'))
+ const result = await withRetry(() => Promise.resolve('ok'), 'test-client', 'test-method')
expect(result).toBe('ok')
})
it('retries on transient error and returns result on success', async () => {
let callCount = 0
- const result = await withRetry('test', () => {
- callCount++
- if (callCount === 1) {
- throw new ConnectError('transient', Code.Unavailable)
- }
- return Promise.resolve('recovered')
- })
+ const result = await withRetry(
+ () => {
+ callCount++
+ if (callCount === 1) {
+ throw new ConnectError('transient', Code.Unavailable)
+ }
+ return Promise.resolve('recovered')
+ },
+ 'test-client',
+ 'test-method'
+ )
expect(result).toBe('recovered')
expect(callCount).toBe(2)
@@ -33,13 +37,17 @@ describe('withRetry', () => {
['Unknown', Code.Unknown],
])('retries on %s', async (_name, code) => {
let callCount = 0
- await withRetry('test', () => {
- callCount++
- if (callCount <= 1) {
- throw new ConnectError('transient', code)
- }
- return Promise.resolve('ok')
- })
+ await withRetry(
+ () => {
+ callCount++
+ if (callCount <= 1) {
+ throw new ConnectError('transient', code)
+ }
+ return Promise.resolve('ok')
+ },
+ 'test-client',
+ 'test-method'
+ )
expect(callCount).toBe(2)
})
@@ -57,10 +65,14 @@ describe('withRetry', () => {
])('does not retry on %s', async (_name, code) => {
let callCount = 0
await expect(
- withRetry('test', () => {
- callCount++
- throw new ConnectError('non-retryable', code)
- })
+ withRetry(
+ () => {
+ callCount++
+ throw new ConnectError('non-retryable', code)
+ },
+ 'test-client',
+ 'test-method'
+ )
).rejects.toThrow(ConnectError)
expect(callCount).toBe(1)
})
@@ -68,10 +80,14 @@ describe('withRetry', () => {
it('does not retry non-ConnectError errors', async () => {
let callCount = 0
await expect(
- withRetry('test', () => {
- callCount++
- throw new Error('plain error')
- })
+ withRetry(
+ () => {
+ callCount++
+ throw new Error('plain error')
+ },
+ 'test-client',
+ 'test-method'
+ )
).rejects.toThrow('plain error')
expect(callCount).toBe(1)
})
@@ -79,10 +95,14 @@ describe('withRetry', () => {
it('throws after max retries exhausted', async () => {
let callCount = 0
await expect(
- withRetry('test', () => {
- callCount++
- throw new ConnectError('unavailable', Code.Unavailable)
- })
+ withRetry(
+ () => {
+ callCount++
+ throw new ConnectError('unavailable', Code.Unavailable)
+ },
+ 'test-client',
+ 'test-method'
+ )
).rejects.toThrow(ConnectError)
// 1 initial + 2 retries = 3 total (default maxRetries=2)
expect(callCount).toBe(3)
@@ -92,11 +112,12 @@ describe('withRetry', () => {
let callCount = 0
await expect(
withRetry(
- 'test',
() => {
callCount++
throw new ConnectError('unavailable', Code.Unavailable)
},
+ 'test-client',
+ 'test-method',
4
)
).rejects.toThrow(ConnectError)
diff --git a/nodejs/src/ingestion/personhog/grpc-retry.ts b/nodejs/src/ingestion/personhog/grpc-retry.ts
index a549fd99c77e..fbbe1c08ce14 100644
--- a/nodejs/src/ingestion/personhog/grpc-retry.ts
+++ b/nodejs/src/ingestion/personhog/grpc-retry.ts
@@ -1,7 +1,7 @@
import { Code, ConnectError } from '@connectrpc/connect'
import { logger } from '../../utils/logger'
-import { grpcErrorType, personhogRetriesTotal } from './metrics'
+import { grpcErrorType, personhogRetriesTotal, personhogTerminalErrorsTotal } from './metrics'
const RETRYABLE_CODES = new Set([
Code.Unavailable,
@@ -23,10 +23,16 @@ function sleep(ms: number): Promise<void> {
/**
* Retry a function with exponential backoff on transient gRPC errors.
* Non-transient errors are thrown immediately.
+ *
+ * Emits `personhog_retries_total` on each retried attempt and
+ * `personhog_terminal_errors_total` when retries are exhausted or the
+ * error is non-retryable — both tagged with method + client + error_type
+ * so they align with `personhog_errors_total` from timedGrpc.
*/
export async function withRetry<T>(
- label: string,
fn: () => Promise<T>,
+ client: string,
+ method: string,
maxRetries: number = 2,
initialDelayMs: number = 50
): Promise<T> {
@@ -37,13 +43,14 @@ export async function withRetry<T>(
} catch (error) {
lastError = error
if (!isRetryable(error) || attempt === maxRetries) {
- logger.error(`[PersonHog] gRPC call failed in ${label}`, {
+ personhogTerminalErrorsTotal.inc({ method, client, error_type: grpcErrorType(error) })
+ logger.error(`[${client}/${method}] gRPC call failed`, {
error: String(error),
})
throw error
}
- personhogRetriesTotal.inc({ source: label, error_type: grpcErrorType(error) })
- logger.warn(`[${label}] Retryable gRPC error, retrying`, {
+ personhogRetriesTotal.inc({ method, client, error_type: grpcErrorType(error) })
+ logger.warn(`[${client}/${method}] Retryable gRPC error, retrying`, {
attempt: attempt + 1,
maxRetries,
error: String(error),
diff --git a/nodejs/src/ingestion/personhog/metrics.ts b/nodejs/src/ingestion/personhog/metrics.ts
index 5073b4e872bd..6f1f1c9b9ca1 100644
--- a/nodejs/src/ingestion/personhog/metrics.ts
+++ b/nodejs/src/ingestion/personhog/metrics.ts
@@ -54,7 +54,13 @@ export const personhogErrorsTotal = new Counter({
export const personhogRetriesTotal = new Counter({
name: 'personhog_retries_total',
help: 'Total PersonHog gRPC retries before success or exhaustion',
- labelNames: ['source', 'error_type'] as const,
+ labelNames: ['method', 'client', 'error_type'] as const,
+})
+
+export const personhogTerminalErrorsTotal = new Counter({
+ name: 'personhog_terminal_errors_total',
+ help: 'PersonHog gRPC errors after retry exhaustion — the request was not fulfilled',
+ labelNames: ['method', 'client', 'error_type'] as const,
})
export function grpcErrorType(error: unknown): string {
diff --git a/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts b/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts
index 2fbab4aaaee4..4e62a460eed5 100644
--- a/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts
+++ b/nodejs/src/ingestion/personhog/personhog-group-read-repository.ts
@@ -28,10 +28,14 @@ export class PersonHogGroupReadRepository implements GroupReadRepository {
group_properties: Record<string, any>
}[]
> {
- return withRetry('PersonHogGroupReadRepository.fetchGroupsByKeys', () =>
- timedGrpc(this.clientLabel, 'fetchGroupsByKeys', () =>
- this.grpcClient.groups.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, callerTag)
- )
+ const method = 'fetchGroupsByKeys'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.groups.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, callerTag)
+ ),
+ this.clientLabel,
+ method
)
}
@@ -39,10 +43,14 @@ export class PersonHogGroupReadRepository implements GroupReadRepository {
teamIds: TeamId[],
callerTag?: string
): Promise<Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]>> {
- return withRetry('PersonHogGroupReadRepository.fetchGroupTypesByTeamIds', () =>
- timedGrpc(this.clientLabel, 'fetchGroupTypesByTeamIds', () =>
- this.grpcClient.groups.fetchGroupTypesByTeamIds(teamIds, callerTag)
- )
+ const method = 'fetchGroupTypesByTeamIds'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.groups.fetchGroupTypesByTeamIds(teamIds, callerTag)
+ ),
+ this.clientLabel,
+ method
)
}
@@ -50,10 +58,14 @@ export class PersonHogGroupReadRepository implements GroupReadRepository {
projectIds: ProjectId[],
callerTag?: string
): Promise<Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]>> {
- return withRetry('PersonHogGroupReadRepository', () =>
- timedGrpc(this.clientLabel, 'fetchGroupTypesByProjectIds', () =>
- this.grpcClient.groups.fetchGroupTypesByProjectIds(projectIds, callerTag)
- )
+ const method = 'fetchGroupTypesByProjectIds'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.groups.fetchGroupTypesByProjectIds(projectIds, callerTag)
+ ),
+ this.clientLabel,
+ method
)
}
}
diff --git a/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts b/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts
index 29f61ff99975..148d745f87f0 100644
--- a/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts
+++ b/nodejs/src/ingestion/personhog/personhog-person-read-repository.ts
@@ -19,10 +19,14 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
) {}
async fetchPerson(teamId: number, distinctId: string, callerTag?: string): Promise<InternalPerson | undefined> {
- const results = await withRetry('PersonHogPersonReadRepository.fetchPerson', () =>
- timedGrpc(this.clientLabel, 'fetchPerson', () =>
- this.grpcClient.persons.fetchPersonsByDistinctIds([{ teamId, distinctId }], callerTag)
- )
+ const method = 'fetchPerson'
+ const results = await withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.persons.fetchPersonsByDistinctIds([{ teamId, distinctId }], callerTag)
+ ),
+ this.clientLabel,
+ method
)
return results.length > 0 ? results[0] : undefined
}
@@ -31,10 +35,14 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
teamPersons: { teamId: TeamId; distinctId: string }[],
callerTag?: string
): Promise<InternalPersonWithDistinctId[]> {
- return withRetry('PersonHogPersonReadRepository.fetchPersonsByDistinctIds', () =>
- timedGrpc(this.clientLabel, 'fetchPersonsByDistinctIds', () =>
- this.grpcClient.persons.fetchPersonsByDistinctIds(teamPersons, callerTag)
- )
+ const method = 'fetchPersonsByDistinctIds'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.persons.fetchPersonsByDistinctIds(teamPersons, callerTag)
+ ),
+ this.clientLabel,
+ method
)
}
@@ -42,10 +50,14 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
teamPersons: { teamId: TeamId; personId: string }[],
callerTag?: string
): Promise<InternalPerson[]> {
- return withRetry('PersonHogPersonReadRepository.fetchPersonsByPersonIds', () =>
- timedGrpc(this.clientLabel, 'fetchPersonsByPersonIds', () =>
- this.grpcClient.persons.fetchPersonsByPersonIds(teamPersons, callerTag)
- )
+ const method = 'fetchPersonsByPersonIds'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.persons.fetchPersonsByPersonIds(teamPersons, callerTag)
+ ),
+ this.clientLabel,
+ method
)
}
@@ -55,15 +67,19 @@ export class PersonHogPersonReadRepository implements PersonReadRepository {
options?: { limitPerPerson?: number },
callerTag?: string
): Promise<Record<string, string[]>> {
- return withRetry('PersonHogPersonReadRepository.fetchDistinctIdsForPersons', () =>
- timedGrpc(this.clientLabel, 'fetchDistinctIdsForPersons', () =>
- this.grpcClient.persons.getDistinctIdsForPersons(
- teamId,
- personIntIds,
- options?.limitPerPerson,
- callerTag
- )
- )
+ const method = 'fetchDistinctIdsForPersons'
+ return withRetry(
+ () =>
+ timedGrpc(this.clientLabel, method, () =>
+ this.grpcClient.persons.getDistinctIdsForPersons(
+ teamId,
+ personIntIds,
+ options?.limitPerPerson,
+ callerTag
+ )
+ ),
+ this.clientLabel,
+ method
)
}
}
diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.py
index bdc109346041..f87453145695 100644
--- a/posthog/personhog_client/interceptor.py
+++ b/posthog/personhog_client/interceptor.py
@@ -8,6 +8,7 @@ from typing import Any
import grpc
from prometheus_client import Counter, Histogram
+from posthog.personhog_client.metrics import PERSONHOG_ERRORS_TOTAL
from posthog.personhog_client.proto import CONSISTENCY_LEVEL_STRONG
_ClientCallDetails = namedtuple(
@@ -33,12 +34,6 @@ PERSONHOG_DJANGO_REQUEST_COUNT = Counter(
labelnames=["method", "status", "client_name"],
)
-PERSONHOG_DJANGO_TIMEOUT_TOTAL = Counter(
- "personhog_django_grpc_timeouts_total",
- "gRPC requests that exceeded their deadline (DEADLINE_EXCEEDED)",
- labelnames=["method", "client_name"],
-)
-
def _method_name(client_call_details: grpc.ClientCallDetails) -> str:
# client_call_details.method is like "/personhog.service.v1.PersonHogService/GetPerson"
@@ -46,6 +41,14 @@ def _method_name(client_call_details: grpc.ClientCallDetails) -> str:
return method.rsplit("/", 1)[-1]
+def _grpc_error_type(code: grpc.StatusCode) -> str:
+ """Convert a gRPC status code to PascalCase to match Node.js and Rust error_type labels."""
+ # grpc.StatusCode.DEADLINE_EXCEEDED.name → "DEADLINE_EXCEEDED"
+ # We need "DeadlineExceeded" to align with Code[error.code] in Node
+ # and format!("{:?}", s.code()) in Rust.
+ return code.name.replace("_", " ").title().replace(" ", "")
+
+
def _with_metadata(
client_call_details: grpc.ClientCallDetails,
extra: Sequence[tuple[str, str]],
@@ -116,15 +119,17 @@ class MetricsInterceptor(grpc.UnaryUnaryClientInterceptor):
code = response.code()
status = code.name if code else "OK"
PERSONHOG_DJANGO_REQUEST_COUNT.labels(method=method, status=status, client_name=self._client_name).inc()
- if code == grpc.StatusCode.DEADLINE_EXCEEDED:
- PERSONHOG_DJANGO_TIMEOUT_TOTAL.labels(method=method, client_name=self._client_name).inc()
+ if code is not None and code != grpc.StatusCode.OK:
+ PERSONHOG_ERRORS_TOTAL.labels(
+ method=method, client=self._client_name, error_type=_grpc_error_type(code)
+ ).inc()
return response
except grpc.RpcError as exc:
code = exc.code()
status = code.name if code else "UNKNOWN"
+ error_type = _grpc_error_type(code) if code else "Unknown"
PERSONHOG_DJANGO_REQUEST_COUNT.labels(method=method, status=status, client_name=self._client_name).inc()
- if code == grpc.StatusCode.DEADLINE_EXCEEDED:
- PERSONHOG_DJANGO_TIMEOUT_TOTAL.labels(method=method, client_name=self._client_name).inc()
+ PERSONHOG_ERRORS_TOTAL.labels(method=method, client=self._client_name, error_type=error_type).inc()
raise
finally:
PERSONHOG_DJANGO_REQUEST_DURATION.labels(method=method, client_name=self._client_name).observe(
diff --git a/posthog/personhog_client/metrics.py b/posthog/personhog_client/metrics.py
index 064c5c23441c..4f10245a7e5d 100644
--- a/posthog/personhog_client/metrics.py
+++ b/posthog/personhog_client/metrics.py
@@ -26,3 +26,9 @@ PERSONHOG_TEAM_MISMATCH_TOTAL = Counter(
"Persons dropped because personhog returned a mismatched team_id",
labelnames=["operation", "client_name"],
)
+
+PERSONHOG_ERRORS_TOTAL = Counter(
+ "personhog_errors_total",
+ "Total PersonHog gRPC errors — every failed gRPC attempt",
+ labelnames=["method", "client", "error_type"],
+)
diff --git a/posthog/personhog_client/test_metrics_interceptor.py b/posthog/personhog_client/test_metrics_interceptor.py
index e5013875f20d..393484dfc95d 100644
--- a/posthog/personhog_client/test_metrics_interceptor.py
+++ b/posthog/personhog_client/test_metrics_interceptor.py
@@ -84,20 +84,22 @@ class TestMetricsInterceptorReturnsBehavior:
interceptor.intercept_unary_unary(_make_raising_continuation(status_code), details, request=b"")
-class TestMetricsInterceptorTimeoutTracking:
- @patch("posthog.personhog_client.interceptor.PERSONHOG_DJANGO_TIMEOUT_TOTAL")
- def test_increments_timeout_counter_on_deadline_exceeded_response(self, mock_timeout_counter):
+class TestMetricsInterceptorErrorTracking:
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_ERRORS_TOTAL")
+ def test_increments_error_counter_on_non_ok_response(self, mock_errors_counter):
interceptor = MetricsInterceptor("test-client")
details = _make_call_details()
- response = _make_error_response(grpc.StatusCode.DEADLINE_EXCEEDED)
+ response = _make_error_response(grpc.StatusCode.UNAVAILABLE)
interceptor.intercept_unary_unary(lambda d, r: response, details, request=b"")
- mock_timeout_counter.labels.assert_called_with(method="GetPerson", client_name="test-client")
- mock_timeout_counter.labels.return_value.inc.assert_called_once()
+ mock_errors_counter.labels.assert_called_with(
+ method="GetPerson", client="test-client", error_type="Unavailable"
+ )
+ mock_errors_counter.labels.return_value.inc.assert_called_once()
- @patch("posthog.personhog_client.interceptor.PERSONHOG_DJANGO_TIMEOUT_TOTAL")
- def test_increments_timeout_counter_on_deadline_exceeded_exception(self, mock_timeout_counter):
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_ERRORS_TOTAL")
+ def test_increments_error_counter_on_rpc_exception(self, mock_errors_counter):
interceptor = MetricsInterceptor("test-client")
details = _make_call_details()
@@ -108,24 +110,16 @@ class TestMetricsInterceptorTimeoutTracking:
request=b"",
)
- mock_timeout_counter.labels.assert_called_with(method="GetPerson", client_name="test-client")
- mock_timeout_counter.labels.return_value.inc.assert_called_once()
-
- @patch("posthog.personhog_client.interceptor.PERSONHOG_DJANGO_TIMEOUT_TOTAL")
- def test_does_not_increment_timeout_counter_on_other_errors(self, mock_timeout_counter):
- interceptor = MetricsInterceptor("test-client")
- details = _make_call_details()
- response = _make_error_response(grpc.StatusCode.UNAVAILABLE)
-
- interceptor.intercept_unary_unary(lambda d, r: response, details, request=b"")
-
- mock_timeout_counter.labels.return_value.inc.assert_not_called()
+ mock_errors_counter.labels.assert_called_with(
+ method="GetPerson", client="test-client", error_type="DeadlineExceeded"
+ )
+ mock_errors_counter.labels.return_value.inc.assert_called_once()
- @patch("posthog.personhog_client.interceptor.PERSONHOG_DJANGO_TIMEOUT_TOTAL")
- def test_does_not_increment_timeout_counter_on_success(self, mock_timeout_counter):
+ @patch("posthog.personhog_client.interceptor.PERSONHOG_ERRORS_TOTAL")
+ def test_does_not_increment_error_counter_on_success(self, mock_errors_counter):
interceptor = MetricsInterceptor("test-client")
details = _make_call_details()
interceptor.intercept_unary_unary(lambda d, r: _make_ok_response(), details, request=b"")
- mock_timeout_counter.labels.return_value.inc.assert_not_called()
+ mock_errors_counter.labels.return_value.inc.assert_not_called()
diff --git a/rust/property-defs-rs/src/group_type_resolver.rs b/rust/property-defs-rs/src/group_type_resolver.rs
index 84c02a9e3e76..a1c0837e7063 100644
--- a/rust/property-defs-rs/src/group_type_resolver.rs
+++ b/rust/property-defs-rs/src/group_type_resolver.rs
@@ -9,7 +9,10 @@ use tracing::{info, warn};
use crate::{
config::Config,
- metrics_consts::{GROUP_TYPE_CACHE, PERSONHOG_RESOLVE_DURATION, PERSONHOG_RESOLVE_ERRORS},
+ metrics_consts::{
+ GROUP_TYPE_CACHE, PERSONHOG_ERRORS_TOTAL, PERSONHOG_RESOLVE_DURATION,
+ PERSONHOG_RESOLVE_ERRORS,
+ },
types::{GroupType, Update},
};
@@ -88,8 +91,19 @@ impl GroupTypeResolver {
let resolved_map = match self.resolve_via_personhog(&to_resolve).await {
Ok(map) => map,
Err(e) => {
- warn!(error = %e, "personhog group type resolution failed");
+ let error_type = e
+ .downcast_ref::<tonic::Status>()
+ .map(|s| format!("{:?}", s.code()))
+ .unwrap_or_else(|| "unknown".to_string());
+ warn!(error = %e, error_type = %error_type, "personhog group type resolution failed");
metrics::counter!(PERSONHOG_RESOLVE_ERRORS).increment(1);
+ metrics::counter!(
+ PERSONHOG_ERRORS_TOTAL,
+ "method" => "GetGroupTypeMappingsByTeamIds",
+ "client" => "property-defs-rs",
+ "error_type" => error_type,
+ )
+ .increment(1);
return Err(e);
}
};
diff --git a/rust/property-defs-rs/src/metrics_consts.rs b/rust/property-defs-rs/src/metrics_consts.rs
index 5faab515a067..2093fc9eeef0 100644
--- a/rust/property-defs-rs/src/metrics_consts.rs
+++ b/rust/property-defs-rs/src/metrics_consts.rs
@@ -36,6 +36,7 @@ pub const ISOLATED_PROPDEFS_DB_SELECTED: &str = "isolated_propdefs_db_selected";
pub const PERSONHOG_RESOLVE_ERRORS: &str = "prop_defs_personhog_resolve_errors";
pub const PERSONHOG_RESOLVE_DURATION: &str = "prop_defs_personhog_resolve_duration_ms";
+pub const PERSONHOG_ERRORS_TOTAL: &str = "personhog_errors_total";
//
// property-defs-rs "v2" batch write path metric keys below