: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
fix(cdp): keep push-api connections open longer than envoy and close idle ones on shutdown (#114254)
Daniel Marchukadd8244b11a2
diff --git a/nodejs/src/messaging/push-subscriptions/idle-connections.test.ts b/nodejs/src/messaging/push-subscriptions/idle-connections.test.tsnew file mode 100644index 000000000000..e8c95e93dfce--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/idle-connections.test.ts@@ -0,0 +1,70 @@+import { Server, createServer } from 'http'+import { AddressInfo, Socket, connect } from 'net'++import { capIdleConnections } from './idle-connections'++describe('capIdleConnections', () => {+ let server: Server+ let port: number+ const sockets: Socket[] = []++ beforeEach(async () => {+ server = createServer((req, res) => {+ if (req.url === '/slow') {+ setTimeout(() => res.end('ok'), 200)+ return+ }+ res.end('ok')+ })+ server.keepAliveTimeout = 60_000+ capIdleConnections(server, 2)+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ port = (server.address() as AddressInfo).port+ })++ afterEach(async () => {+ sockets.splice(0).forEach((socket) => socket.destroy())+ await new Promise((resolve) => server.close(resolve))+ })++ const open = async (): Promise<Socket> => {+ const socket = connect(port, '127.0.0.1')+ sockets.push(socket)+ await new Promise((resolve) => socket.once('connect', resolve))+ return socket+ }++ const request = (socket: Socket, path = '/'): Promise<void> =>+ new Promise((resolve) => {+ socket.once('data', () => resolve())+ socket.write(`GET ${path} HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n`)+ })++ const isOpen = async (socket: Socket): Promise<boolean> => {+ await new Promise((resolve) => setTimeout(resolve, 50))+ return !socket.destroyed && !socket.readableEnded+ }++ it('closes the longest-idle connections beyond the limit and keeps the rest', async () => {+ const [first, second, third] = [await open(), await open(), await open()]+ for (const socket of [first, second, third]) {+ await request(socket)+ }++ expect(await isOpen(first)).toBe(false)+ expect(await isOpen(second)).toBe(true)+ expect(await isOpen(third)).toBe(true)+ await request(second)+ })++ it('never closes a connection that is serving a request', async () => {+ const busy = await open()+ const finished = request(busy, '/slow')+ for (let i = 0; i < 3; i++) {+ await request(await open())+ }++ await finished+ expect(await isOpen(busy)).toBe(true)+ })+})diff --git a/nodejs/src/messaging/push-subscriptions/idle-connections.ts b/nodejs/src/messaging/push-subscriptions/idle-connections.tsnew file mode 100644index 000000000000..ad9ed91dbfca--- /dev/null+++ b/nodejs/src/messaging/push-subscriptions/idle-connections.ts@@ -0,0 +1,38 @@+import { Server } from 'http'+import { Socket } from 'net'+import { Counter } from 'prom-client'++const evictedIdleConnections = new Counter({+ name: 'push_api_idle_connections_evicted_total',+ help: 'Idle keep-alive connections closed because the server held more than its idle limit.',+})++/** Closes the longest-idle keep-alive connections once more than `maxIdle` sit idle, so a long+ * keep-alive timeout cannot be used to pile up open sockets. A connection serving a request is never+ * closed here. */+export function capIdleConnections(server: Server, maxIdle: number): void {+ // A Set iterates in insertion order, so the first entry is the connection idle the longest.+ const idle = new Set<Socket>()++ server.on('connection', (socket: Socket) => {+ socket.once('close', () => idle.delete(socket))+ })+ server.on('request', (req, res) => {+ const socket = req.socket+ idle.delete(socket)+ res.once('finish', () => {+ if (socket.destroyed) {+ return+ }+ idle.add(socket)+ for (const oldest of idle) {+ if (idle.size <= maxIdle) {+ break+ }+ idle.delete(oldest)+ oldest.destroy()+ evictedIdleConnections.inc()+ }+ })+ })+}diff --git a/nodejs/src/servers/push-api-server.ts b/nodejs/src/servers/push-api-server.tsindex e51044d9770a..d518e3d24e60 100644--- a/nodejs/src/servers/push-api-server.ts+++ b/nodejs/src/servers/push-api-server.ts@@ -6,6 +6,7 @@ import { PostgresRouter, PostgresRouterConfig } from '~/common/utils/db/postgresimport { isProdEnv, isTestEnv } from '~/common/utils/env-utils'import { GeoIPService } from '~/common/utils/geoip'import { logger } from '~/common/utils/logger'+import { capIdleConnections } from '~/messaging/push-subscriptions/idle-connections'import { ProjectTokenLookup } from '~/messaging/push-subscriptions/project-token-lookup'import { DryRunPushCaptureService, PushCaptureService } from '~/messaging/push-subscriptions/push-capture'import { createPushSubscriptionsHandler } from '~/messaging/push-subscriptions/push-subscriptions-http'@@ -16,6 +17,8 @@ import { CommonConfig } from '../common/config'import { HealthCheckResult, HealthCheckResultError, HealthCheckResultOk, PluginServerService } from '../types'import { BaseServerConfig, CleanupResources, NodeServer, ServerLifecycle } from './base-server'+const MAX_IDLE_CONNECTIONS = 1_000+export type PushApiConfig = {PUSH_API_PORT: numberPUSH_API_HOST: string@@ -129,7 +132,15 @@ export class PushApiServer implements NodeServer {resolve()return}- this.pushServer.close(() => resolve())+ const server = this.pushServer+ // close() ends only the connections idle at that moment. A connection that finishes its+ // request afterwards stays open until the keep-alive timeout, which is longer than a pod's+ // grace period, so the idle ones are closed until the server stops.+ const closeIdle = setInterval(() => server.closeIdleConnections(), 100)+ server.close(() => {+ clearInterval(closeIdle)+ resolve()+ })})},healthcheck: () => this.isHealthy(),@@ -176,7 +187,11 @@ export class PushApiServer implements NodeServer {// endpoint is starved of connections rather than of CPU.server.headersTimeout = 10_000server.requestTimeout = 15_000- server.keepAliveTimeout = 30_000+ // Envoy keeps an idle upstream connection for up to an hour. If node closes it first, a request+ // Envoy sends at that moment fails with a 503, so the idle timeout outlasts Envoy's.+ server.keepAliveTimeout = 65 * 60_000+ // Envoy pools far fewer connections than this, so only a client piling up idle sockets hits it.+ capIdleConnections(server, MAX_IDLE_CONNECTIONS)return new Promise((resolve, reject) => {server.once('error', (error) => {