: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(nodejs): measure DNS resolution time for external requests (#111751)
Meikel Ratz849e05677446
diff --git a/nodejs/src/common/utils/request.test.ts b/nodejs/src/common/utils/request.test.tsindex 76f98d3c7466..2c5458daaedf 100644--- a/nodejs/src/common/utils/request.test.ts+++ b/nodejs/src/common/utils/request.test.ts@@ -2,6 +2,7 @@ import dns from 'dns/promises'import { range } from 'lodash'import http from 'node:http'import net, { AddressInfo } from 'node:net'+import { register } from 'prom-client'import { getExternalRequestConfig } from '~/common/config'@@ -361,6 +362,28 @@ describe('fetch', () => {// This will fail to connect since it's a mock DNS result, but it should NOT throw SecureRequestErrorawait expect(fetch(`http://example.com`)).rejects.not.toThrow(SecureRequestError) // nosemgrep: typescript.react.security.react-insecure-request.react-insecure-request})++ // A gauge that is incremented but not decremented drifts up forever, and nothing else reads this one, so a+ // leak on either path would go unnoticed until it had already made the metric useless.+ it.each([+ [+ 'a lookup that resolves',+ () => jest.mocked(dns.lookup).mockResolvedValue([{ address: '10.0.0.1', family: 4 }] as any),+ ],+ ['a lookup that rejects', () => jest.mocked(dns.lookup).mockRejectedValue(new Error('ENOTFOUND'))],+ ])('releases the in-flight DNS gauge after %s', async (_name, applyMock) => {+ const readGauge = async (): Promise<number> =>+ (await register.getSingleMetric('node_dns_lookups_in_flight')!.get()).values[0].value++ applyMock()+ const before = await readGauge()++ // nosemgrep: typescript.react.security.react-insecure-request.react-insecure-request+ await expect(fetch(`http://example.com`)).rejects.toThrow()++ expect(dns.lookup).toHaveBeenCalled()+ expect(await readGauge()).toEqual(before)+ })})describe('parallel requests execution', () => {diff --git a/nodejs/src/common/utils/request.ts b/nodejs/src/common/utils/request.tsindex 5b9159406313..c9ead39bf42b 100644--- a/nodejs/src/common/utils/request.ts+++ b/nodejs/src/common/utils/request.ts@@ -2,7 +2,7 @@ import { LookupAddress } from 'dns'import dns from 'dns/promises'import * as ipaddr from 'ipaddr.js'import net from 'node:net'-import { Counter, Gauge } from 'prom-client'+import { Counter, Gauge, Histogram } from 'prom-client'// eslint-disable-next-line no-restricted-importsimport {Agent,@@ -56,6 +56,23 @@ const inflightExternalRequests = new Gauge({help: 'Number of currently inflight external HTTP requests (undici). Use as HPA scaling metric for cdp-cyclotron-worker.',})+// The connect timeout is a single budget covering DNS resolution, TCP and TLS, and only the total request duration is+// measured elsewhere, so a connect timeout does not say which phase consumed the budget. Resolution is the phase that+// runs in this process, so it is the one that can be measured here. The duration separates a slow resolver path from a+// fast one, and the in-flight gauge separates lookups that queue behind other lookups from lookups that are themselves+// slow. Neither carries the hostname as a label, because destination hostnames are customer-supplied and unbounded.+const dnsLookupDuration = new Histogram({+ name: 'node_dns_lookup_duration_ms',+ help: 'Duration of dns.lookup() for an external hostname, in milliseconds',+ labelNames: ['outcome'],+ buckets: [1, 5, 10, 25, 50, 100, 250, 500, 1000, 2000, 3000, 5000, 10000],+})++const dnsLookupsInFlight = new Gauge({+ name: 'node_dns_lookups_in_flight',+ help: 'Number of dns.lookup() calls currently awaiting a result',+})+// NOTE: This isn't exactly fetch - it's meant to be very close but limited to only options we actually want to exposeexport type FetchOptions = {method?: string@@ -207,10 +224,16 @@ function isIPv4(addr: ipaddr.IPv4 | ipaddr.IPv6): addr is ipaddr.IPv4 {async function staticLookupAsync(hostname: string): Promise<LookupAddress[]> {let addrinfo: LookupAddress[]const validAddrinfo: LookupAddress[] = []+ const lookupStartedAt = performance.now()+ dnsLookupsInFlight.inc()try {addrinfo = await dns.lookup(hostname, { all: true })+ dnsLookupDuration.observe({ outcome: 'success' }, performance.now() - lookupStartedAt)} catch {+ dnsLookupDuration.observe({ outcome: 'failure' }, performance.now() - lookupStartedAt)throw new ResolutionError('Invalid hostname')+ } finally {+ dnsLookupsInFlight.dec()}const resolvedIps = addrinfo.map((a) => a.address)for (const addrInfo of addrinfo) {