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(cdp): record batch audience fetch duration by endpoint and outcome (#112432)

Daniel Marchukf0951becd162
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts
index a465f6acd6f3..bb89a1d422fd 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.test.ts
@@ -341,4 +341,50 @@ describe('HogFlowBatchPersonQueryService', () => {
)
})
})
+
+ describe('audience fetch duration', () => {
+ const fetchCount = async (endpoint: string, outcome: string): Promise<number> => {
+ const metric = await register.getSingleMetric('cdp_batch_hog_flow_audience_fetch_duration_seconds')?.get()
+ const values = (metric?.values ?? []) as Array<{
+ metricName?: string
+ value: number
+ labels: { endpoint?: string; outcome?: string }
+ }>
+ return (
+ values.find(
+ (value) =>
+ value.metricName === 'cdp_batch_hog_flow_audience_fetch_duration_seconds_count' &&
+ value.labels.endpoint === endpoint &&
+ value.labels.outcome === outcome
+ )?.value ?? 0
+ )
+ }
+
+ // The alert reads the outcome label; a fetch filed under the wrong one keeps it silent.
+ it.each([
+ [
+ 'a 200 response',
+ 'success',
+ {
+ fetchResponse: createFetchResponse(200, { users_affected: [], cursor: null, has_more: false }),
+ fetchError: null,
+ },
+ ],
+ ['a 500 response', 'error', { fetchResponse: createFetchResponse(500, 'boom'), fetchError: null }],
+ ['a transport error', 'error', { fetchResponse: null, fetchError: new Error('network down') }],
+ [
+ 'a client timeout',
+ 'timeout',
+ { fetchResponse: null, fetchError: Object.assign(new Error('aborted'), { name: 'TimeoutError' }) },
+ ],
+ ])('records %s under outcome %s', async (_name, outcome, result) => {
+ const service = createService()
+ const before = await fetchCount('user_blast_radius_persons', outcome)
+
+ fetchMock.mockResolvedValue(result as MockedInternalFetchResult)
+ await service.getBlastRadiusPersons(team, filters).catch(() => undefined)
+
+ expect(await fetchCount('user_blast_radius_persons', outcome)).toBe(before + 1)
+ })
+ })
})
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts
index b30c7c6e00f0..1159071d1d26 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-batch-person-query.service.ts
@@ -1,4 +1,4 @@
-import { Counter } from 'prom-client'
+import { Counter, Histogram } from 'prom-client'
import { InternalFetchService } from '~/common/services/internal-fetch'
import { parseJSON } from '~/common/utils/json-parse'
@@ -31,6 +31,14 @@ const counterAudienceFetchTimeout = new Counter({
labelNames: ['endpoint'],
})
+// Bucket edges sit around the fetch budget; instrumented_function_duration_seconds jumps from 25.6s to 102.4s.
+const histogramAudienceFetchDuration = new Histogram({
+ name: 'cdp_batch_hog_flow_audience_fetch_duration_seconds',
+ help: 'Wall time of one audience fetch for a batch hog flow, from request to response body read',
+ labelNames: ['endpoint', 'outcome'], // success | timeout | error
+ buckets: [1, 2, 5, 10, 20, 30, 40, 50, 60, 90, 120],
+})
+
export type AudienceFetchEndpoint = 'user_blast_radius' | 'user_blast_radius_persons' | 'account_audience'
/**
@@ -80,26 +88,83 @@ export class HogFlowBatchPersonQueryService {
* type and its own counter, because the audience query is too slow for the budget. Any
* other transport error keeps its original type.
*/
- private failFetch(endpoint: AudienceFetchEndpoint, urlPath: string, fetchError: Error | null): never {
+ private failFetch(
+ endpoint: AudienceFetchEndpoint,
+ urlPath: string,
+ fetchError: Error | null,
+ durationMs: number
+ ): never {
if (isTimeoutError(fetchError)) {
counterAudienceFetchTimeout.labels({ endpoint }).inc()
+ histogramAudienceFetchDuration.labels({ endpoint, outcome: 'timeout' }).observe(durationMs / 1000)
logger.error('Audience fetch timed out', {
endpoint,
urlPath,
+ durationMs,
timeoutMs: this.audienceFetchTimeoutMs,
error: serializeError(fetchError),
})
throw new AudienceFetchTimeoutError(endpoint, this.audienceFetchTimeoutMs)
}
+ histogramAudienceFetchDuration.labels({ endpoint, outcome: 'error' }).observe(durationMs / 1000)
logger.error('Error fetching audience from Django', {
endpoint,
urlPath,
+ durationMs,
error: serializeError(fetchError),
})
throw fetchError ?? new Error(`Audience fetch to ${endpoint} returned no response`)
}
+ private async fetchAudience<T>(
+ endpoint: AudienceFetchEndpoint,
+ urlPath: `/${string}`,
+ body: Record<string, unknown>,
+ failureLabel: string
+ ): Promise<T> {
+ const startedAt = performance.now()
+ const { fetchResponse, fetchError } = await this.internalFetchService.fetch({
+ urlPath,
+ fetchParams: {
+ method: 'POST',
+ timeoutMs: this.audienceFetchTimeoutMs,
+ body: JSON.stringify(body),
+ },
+ })
+ const elapsedMs = (): number => Math.round(performance.now() - startedAt)
+
+ if (!fetchResponse || fetchError) {
+ this.failFetch(endpoint, urlPath, fetchError, elapsedMs())
+ }
+
+ const text = await fetchResponse.text()
+ const durationMs = elapsedMs()
+
+ if (fetchResponse.status !== 200) {
+ histogramAudienceFetchDuration.labels({ endpoint, outcome: 'error' }).observe(durationMs / 1000)
+ logger.error(`Failed to fetch ${failureLabel} from Django`, {
+ status: fetchResponse.status,
+ error: text,
+ urlPath,
+ durationMs,
+ })
+ throw new Error(`Failed to fetch ${failureLabel}: ${fetchResponse.status} ${text}`)
+ }
+
+ histogramAudienceFetchDuration.labels({ endpoint, outcome: 'success' }).observe(durationMs / 1000)
+ if (durationMs * 2 > this.audienceFetchTimeoutMs) {
+ // The histogram has no team label; the urlPath here does.
+ logger.warn('Slow audience fetch', {
+ endpoint,
+ urlPath,
+ durationMs,
+ timeoutMs: this.audienceFetchTimeoutMs,
+ })
+ }
+ return parseJSON(text) as T
+ }
+
/**
* Get count of users affected by filters
*/
@@ -112,35 +177,12 @@ export class HogFlowBatchPersonQueryService {
const urlPath = `/api/projects/${team.id}/internal/hog_flows/user_blast_radius` as const
try {
- const { fetchResponse, fetchError } = await this.internalFetchService.fetch({
+ return await this.fetchAudience<BlastRadiusResponse>(
+ 'user_blast_radius',
urlPath,
- fetchParams: {
- method: 'POST',
- timeoutMs: this.audienceFetchTimeoutMs,
- body: JSON.stringify({
- filters,
- group_type_index: groupTypeIndex,
- }),
- },
- })
-
- if (!fetchResponse || fetchError) {
- this.failFetch('user_blast_radius', urlPath, fetchError)
- }
-
- if (fetchResponse.status !== 200) {
- const errorText = await fetchResponse.text()
- logger.error('Failed to fetch blast radius from Django', {
- status: fetchResponse.status,
- error: errorText,
- urlPath,
- })
- throw new Error(`Failed to fetch blast radius: ${fetchResponse.status} ${errorText}`)
- }
-
- const data = parseJSON(await fetchResponse.text()) as BlastRadiusResponse
-
- return data
+ { filters, group_type_index: groupTypeIndex },
+ 'blast radius'
+ )
} catch (error) {
logger.error('Error calling blast radius endpoint', { error: serializeError(error), urlPath })
throw error
@@ -163,37 +205,17 @@ export class HogFlowBatchPersonQueryService {
const urlPath = `/api/projects/${team.id}/internal/hog_flows/user_blast_radius_persons` as const
try {
- const { fetchResponse, fetchError } = await this.internalFetchService.fetch({
+ return await this.fetchAudience<BlastRadiusPersonsResponse>(
+ 'user_blast_radius_persons',
urlPath,
- fetchParams: {
- method: 'POST',
- timeoutMs: this.audienceFetchTimeoutMs,
- body: JSON.stringify({
- filters,
- group_type_index: groupTypeIndex,
- cursor: cursor || null,
- dedupe_key: dedupeKey ?? null,
- }),
+ {
+ filters,
+ group_type_index: groupTypeIndex,
+ cursor: cursor || null,
+ dedupe_key: dedupeKey ?? null,
},
- })
-
- if (!fetchResponse || fetchError) {
- this.failFetch('user_blast_radius_persons', urlPath, fetchError)
- }
-
- if (fetchResponse.status !== 200) {
- const errorText = await fetchResponse.text()
- logger.error('Failed to fetch blast radius persons from Django', {
- status: fetchResponse.status,
- error: errorText,
- urlPath,
- })
- throw new Error(`Failed to fetch blast radius persons: ${fetchResponse.status} ${errorText}`)
- }
-
- const data = parseJSON(await fetchResponse.text()) as BlastRadiusPersonsResponse
-
- return data
+ 'blast radius persons'
+ )
} catch (error) {
logger.error('Error calling blast radius persons endpoint', { error: serializeError(error), urlPath })
throw error
@@ -211,35 +233,12 @@ export class HogFlowBatchPersonQueryService {
const urlPath = `/api/projects/${team.id}/internal/hog_flows/account_audience` as const
try {
- const { fetchResponse, fetchError } = await this.internalFetchService.fetch({
+ return await this.fetchAudience<AccountAudienceResponse>(
+ 'account_audience',
urlPath,
- fetchParams: {
- method: 'POST',
- timeoutMs: this.audienceFetchTimeoutMs,
- body: JSON.stringify({
- filters,
- cursor: cursor || null,
- }),
- },
- })
-
- if (!fetchResponse || fetchError) {
- this.failFetch('account_audience', urlPath, fetchError)
- }
-
- if (fetchResponse.status !== 200) {
- const errorText = await fetchResponse.text()
- logger.error('Failed to fetch account audience from Django', {
- status: fetchResponse.status,
- error: errorText,
- urlPath,
- })
- throw new Error(`Failed to fetch account audience: ${fetchResponse.status} ${errorText}`)
- }
-
- const data = parseJSON(await fetchResponse.text()) as AccountAudienceResponse
-
- return data
+ { filters, cursor: cursor || null },
+ 'account audience'
+ )
} catch (error) {
logger.error('Error calling account audience endpoint', { error: serializeError(error), urlPath })
throw error