: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cdp): add a separately tunable timeout for third-party requests (#80846)
Daniel Marchuk461960bf9434
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 352422f6ffd7..6994e3521213 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -8,6 +8,20 @@ export const DEFAULT_HTTP_SERVER_PORT = 6738// (mirrors LOCAL_DEV_INTERNAL_API_SECRET on the Django side).export const LOCAL_DEV_INTERNAL_API_SECRET = 'posthog123'+/**+ * Response budget for a request to a host we don't run, used by `fetch`/`legacyFetch` in+ * common/utils/request.ts. A CDP destination points at whatever API the customer configured, which+ * is routinely in another region and under no latency obligation to us, so it has different needs+ * from EXTERNAL_REQUEST_TIMEOUT_MS, which is sized for calls between our own services on the same+ * network.+ *+ * Starts equal to the internal budget so the split changes no behavior on its own. Raise it with+ * EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS to buy slower third-party APIs more headroom; an+ * unanswered request holds its worker slot for the whole budget, so the cost lands on+ * cdp_http_inflight_requests.+ */+export const DEFAULT_THIRD_PARTY_REQUEST_TIMEOUT_MS = 3000+export enum KafkaSaslMechanism {Plain = 'plain',ScramSha256 = 'scram-sha-256',@@ -174,7 +188,10 @@ export type CommonConfig = BaseServerConfig & {HOGFLOW_SCHEDULER_POLL_INTERVAL_MS: numberHOGFLOW_SCHEDULER_MAX_POLL_INTERVAL_MS: numberHOGFLOW_SCHEDULER_HEALTH_TIMEOUT_MS: number+ // Despite the EXTERNAL_REQUEST_ prefix this one only reaches `internalFetch`, so it is the+ // budget for calls to our own services. Third-party hosts use the sibling below.EXTERNAL_REQUEST_TIMEOUT_MS: number+ EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS: numberEXTERNAL_REQUEST_CONNECT_TIMEOUT_MS: numberEXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: numberEXTERNAL_REQUEST_CONNECTIONS: number@@ -201,6 +218,7 @@ export type CommonConfig = BaseServerConfig & {export type ExternalRequestConfig = Pick<CommonConfig,| 'EXTERNAL_REQUEST_TIMEOUT_MS'+ | 'EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS'| 'EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS'| 'EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS'| 'EXTERNAL_REQUEST_CONNECTIONS'@@ -209,6 +227,9 @@ export type ExternalRequestConfig = Pick<export function getExternalRequestConfig(): ExternalRequestConfig {return {EXTERNAL_REQUEST_TIMEOUT_MS: Number(process.env.EXTERNAL_REQUEST_TIMEOUT_MS ?? 3000),+ EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS: Number(+ process.env.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS ?? DEFAULT_THIRD_PARTY_REQUEST_TIMEOUT_MS+ ),EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS: Number(process.env.EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS ?? 3000),EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: Number(process.env.EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS ?? 10000),EXTERNAL_REQUEST_CONNECTIONS: Number(process.env.EXTERNAL_REQUEST_CONNECTIONS ?? 500),@@ -352,6 +373,7 @@ export function getDefaultCommonConfig(): CommonConfig {HOGFLOW_SCHEDULER_MAX_POLL_INTERVAL_MS: 5 * 60_000,HOGFLOW_SCHEDULER_HEALTH_TIMEOUT_MS: 10 * 60_000,EXTERNAL_REQUEST_TIMEOUT_MS: 3000,+ EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS: DEFAULT_THIRD_PARTY_REQUEST_TIMEOUT_MS,EXTERNAL_REQUEST_CONNECT_TIMEOUT_MS: 3000,EXTERNAL_REQUEST_KEEP_ALIVE_TIMEOUT_MS: 10000,EXTERNAL_REQUEST_CONNECTIONS: 500,diff --git a/nodejs/src/common/utils/request.test.ts b/nodejs/src/common/utils/request.test.tsindex e92308bdf966..d768b26bffd3 100644--- a/nodejs/src/common/utils/request.test.ts+++ b/nodejs/src/common/utils/request.test.ts@@ -3,8 +3,17 @@ import { range } from 'lodash'import http from 'node:http'import { AddressInfo } from 'node:net'+import { getExternalRequestConfig } from '~/common/config'+import { parseJSON } from './json-parse'-import { SecureRequestError, fetch, internalFetch, legacyFetch, raiseIfUserProvidedUrlUnsafe } from './request'+import {+ FetchOptions,+ SecureRequestError,+ fetch,+ internalFetch,+ legacyFetch,+ raiseIfUserProvidedUrlUnsafe,+} from './request'const realDnsLookup = jest.requireActual('dns/promises').lookupjest.mock('dns/promises', () => ({@@ -119,6 +128,45 @@ describe('fetch', () => {}})+ // The split is only worth anything if `fetch` reads the third-party setting and+ // `internalFetch` does not. Wiring either one to the other's budget fails silently: raising+ // the third-party timeout would then do nothing, or internal calls would quietly inherit it.+ it('resolves each entry point against its own timeout setting', async () => {+ const originalNodeEnv = process.env.NODE_ENV+ process.env.NODE_ENV = 'test'+ process.env.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS = '7654'+ try {+ await jest.isolateModulesAsync(async () => {+ // Re-import against the isolated registry: request.ts reads the config once, at+ // module load, so the override only lands on a fresh copy.+ const fresh = require('./request')+ const thirdPartyOptions: FetchOptions = {}+ const internalOptions: FetchOptions = {}++ await fresh.fetch(baseUrl, thirdPartyOptions)+ await fresh.internalFetch(baseUrl, internalOptions)++ expect(thirdPartyOptions.timeoutMs).toBe(7654)+ expect(internalOptions.timeoutMs).toBe(getExternalRequestConfig().EXTERNAL_REQUEST_TIMEOUT_MS)+ })+ } finally {+ delete process.env.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS+ process.env.NODE_ENV = originalNodeEnv+ }+ }, 10000)++ it('keeps a timeout the caller set explicitly', async () => {+ const originalNodeEnv = process.env.NODE_ENV+ process.env.NODE_ENV = 'test'+ try {+ const options: FetchOptions = { timeoutMs: 1234 }+ await fetch(baseUrl, options)+ expect(options.timeoutMs).toBe(1234)+ } finally {+ process.env.NODE_ENV = originalNodeEnv+ }+ })+it.each([['http://[::ffff:169.254.169.254]/latest/api/token', 'IPv6-mapped IMDS'],['http://[::ffff:127.0.0.1]/', 'IPv6-mapped loopback'],diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.tsindex 2689f327a9d8..4dacfd6c8a55 100644--- a/nodejs/src/common/utils/request.ts+++ b/nodejs/src/common/utils/request.ts@@ -332,7 +332,12 @@ async function readAndDestroyBody(body: Dispatcher.ResponseData['body']): Promisreturn text}-export async function _fetch(url: string, options: FetchOptions = {}, dispatcher: Dispatcher): Promise<FetchResponse> {+export async function _fetch(+ url: string,+ options: FetchOptions = {},+ dispatcher: Dispatcher,+ defaultTimeoutMs: number = requestConfig.EXTERNAL_REQUEST_TIMEOUT_MS+): Promise<FetchResponse> {let parsed: URLtry {parsed = new URL(url)@@ -344,7 +349,7 @@ export async function _fetch(url: string, options: FetchOptions = {}, dispatcherthrow new Error('URL must have HTTP or HTTPS protocol and a valid hostname')}- options.timeoutMs = options.timeoutMs ?? requestConfig.EXTERNAL_REQUEST_TIMEOUT_MS+ options.timeoutMs = options.timeoutMs ?? defaultTimeoutMsconst result = await request(parsed.toString(), {method: options.method ?? 'GET',@@ -399,13 +404,19 @@ export async function internalFetch(url: string, options: FetchOptions = {}): Prreturn await _fetch(url, options, sharedInsecureAgent)}+/**+ * Requests to a host we don't run, meaning CDP destinations and anything else pointed at a+ * customer-supplied URL. These take the third-party response budget, which is tunable separately+ * from the internal-service one that `internalFetch` keeps; see+ * DEFAULT_THIRD_PARTY_REQUEST_TIMEOUT_MS.+ */export async function fetch(url: string, options: FetchOptions = {}): Promise<FetchResponse> {const parsed = new URL(url)validateHostnameIPLiteral(parsed.hostname, !isProdEnv())inflightExternalRequests.inc()try {const dispatcher = options.allowH2 ? sharedSecureH2Agent : sharedSecureAgent- return await _fetch(url, options, dispatcher)+ return await _fetch(url, options, dispatcher, requestConfig.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS)} finally {inflightExternalRequests.dec()}@@ -428,7 +439,7 @@ export function legacyFetch(input: RequestInfo, options?: RequestInit): Promise<const requestOptions = options ?? {}requestOptions.dispatcher = sharedSecureAgent- requestOptions.signal = AbortSignal.timeout(requestConfig.EXTERNAL_REQUEST_TIMEOUT_MS)+ requestOptions.signal = AbortSignal.timeout(requestConfig.EXTERNAL_REQUEST_THIRD_PARTY_TIMEOUT_MS)return undiciFetch(parsed.toString(), requestOptions)}