: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(ingestion): retry transient event schema enforcement loads (#78192)
Paweł Ledwońccbaad3fa110
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.tsindex 4c3ebdca8c5b..3d0a698a065d 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-manager.service.ts@@ -3,7 +3,7 @@ import { Counter } from 'prom-client'import { HogFlow } from '~/cdp/schema/hogflow'import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'import { parseJSON } from '~/common/utils/json-parse'-import { LazyLoader } from '~/common/utils/lazy-loader'+import { DEFAULT_LOADER_RETRY, LazyLoader } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'import { PubSub } from '~/common/utils/pubsub'@@ -64,7 +64,7 @@ export class HogFlowManagerService {refreshBackgroundAgeMs: 30 * 1000,// Absorb transient Postgres blips inside a single load attempt so failed background// refreshes don't re-fire at caller QPS and hard-cap refreshes don't fail the batch.- loaderRetry: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },+ loaderRetry: DEFAULT_LOADER_RETRY,}this.lazyLoaderByTeam = new LazyLoader({diff --git a/nodejs/src/common/groups/readonly-group-type-manager.ts b/nodejs/src/common/groups/readonly-group-type-manager.tsindex 1da7ab208d25..66acf9c757dd 100644--- a/nodejs/src/common/groups/readonly-group-type-manager.ts+++ b/nodejs/src/common/groups/readonly-group-type-manager.ts@@ -1,8 +1,13 @@import { GroupReadRepository } from '~/common/groups/repositories/group-repository.interface'import { timeoutGuard } from '~/common/utils/db/utils'-import { LazyLoader } from '~/common/utils/lazy-loader'+import { LazyLoader, LoaderRetryOptions } from '~/common/utils/lazy-loader'import { GroupTypeToColumnIndex, GroupTypesByProjectId, ProjectId } from '~/types'+export interface ReadOnlyGroupTypeManagerOptions {+ /** Retry transient group-type-load failures (e.g. a Postgres pooler blip) instead of letting them propagate. */+ loaderRetry?: LoaderRetryOptions+}+/*** Read-only group type manager backed by a GroupReadRepository. Provides* cached lookups of project → group type mappings without write capability.@@ -12,11 +17,15 @@ import { GroupTypeToColumnIndex, GroupTypesByProjectId, ProjectId } from '~/typeexport class ReadOnlyGroupTypeManager {private loader: LazyLoader<GroupTypeToColumnIndex>- constructor(private groupRepository: GroupReadRepository) {+ constructor(+ private groupRepository: GroupReadRepository,+ options?: ReadOnlyGroupTypeManagerOptions+ ) {this.loader = new LazyLoader({name: 'ReadOnlyGroupTypeManager',refreshAgeMs: 30_000,refreshJitterMs: 0,+ loaderRetry: options?.loaderRetry,loader: async (projectIds: string[]) => {const response: Record<string, GroupTypeToColumnIndex> = {}const timeout = timeoutGuard(`Still running "fetchGroupTypes". Timeout warning after 30 sec!`)diff --git a/nodejs/src/common/utils/db/postgres.test.ts b/nodejs/src/common/utils/db/postgres.test.tsnew file mode 100644index 000000000000..b6a666134c70--- /dev/null+++ b/nodejs/src/common/utils/db/postgres.test.ts@@ -0,0 +1,31 @@+import { DependencyUnavailableError } from './error'+import { PostgresUse, handlePostgresError, isTransientPgError } from './postgres'++describe('transient postgres error classification', () => {+ test.each([+ ['connect ECONNREFUSED 10.0.0.1:6543', true],+ ['connect EHOSTUNREACH 10.0.0.1:6543', true],+ ['pooler is shutting down', true],+ ['server conn crashed?', true],+ ['duplicate key value violates unique constraint', false],+ ['syntax error at or near "SELCT"', false],+ ])('isTransientPgError(%s) -> %s', (message, expected) => {+ expect(isTransientPgError(new Error(message))).toBe(expected)+ })++ test.each([undefined, null, 'a plain string', new Error()])('isTransientPgError(%p) -> false', (value) => {+ expect(isTransientPgError(value)).toBe(false)+ })++ it('wraps transient errors in a retriable DependencyUnavailableError', () => {+ expect(() => handlePostgresError(new Error('pooler is shutting down'), PostgresUse.PERSONS_WRITE)).toThrow(+ expect.objectContaining({ name: 'DependencyUnavailableError', isRetriable: true })+ )+ })++ it('does nothing for non-transient errors', () => {+ expect(() =>+ handlePostgresError(new Error('duplicate key value violates unique constraint'), PostgresUse.PERSONS_WRITE)+ ).not.toThrow(DependencyUnavailableError)+ })+})diff --git a/nodejs/src/common/utils/db/postgres.ts b/nodejs/src/common/utils/db/postgres.tsindex 4adab5a9d913..3d672aecff93 100644--- a/nodejs/src/common/utils/db/postgres.ts+++ b/nodejs/src/common/utils/db/postgres.ts@@ -52,9 +52,11 @@ const POSTGRES_UNAVAILABLE_ERROR_MESSAGES = ['Connection terminated unexpectedly','ECONNREFUSED','ECONNRESET', // Connection reset by peer, e.g. PgBouncer/PG closed an idle or in-flight connection+ 'EHOSTUNREACH', // No route to host, e.g. the PgBouncer pod's IP vanished during a restart'ETIMEDOUT','query_wait_timeout', // Waiting on PG bouncer to give us a slot'server login has been failing', // PgBouncer cannot authenticate with upstream PG+ 'pooler is shutting down', // PgBouncer terminating client connections during a restart]export function isTransientPgError(err: unknown): boolean {diff --git a/nodejs/src/common/utils/event-schema-enforcement-manager.ts b/nodejs/src/common/utils/event-schema-enforcement-manager.tsindex fda0a1ec8084..f6543c155992 100644--- a/nodejs/src/common/utils/event-schema-enforcement-manager.ts+++ b/nodejs/src/common/utils/event-schema-enforcement-manager.ts@@ -1,7 +1,7 @@import { EventSchemaEnforcement } from '~/types'import { PostgresRouter, PostgresUse } from './db/postgres'-import { LazyLoader } from './lazy-loader'+import { LazyLoader, LoaderRetryOptions } from './lazy-loader'/*** Raw row from the database query - one row per property per event.@@ -23,14 +23,23 @@ interface RawSchemaPropertyRow {/** Map from event_name to schema for O(1) lookups */export type EventSchemaMap = Map<string, EventSchemaEnforcement>+export interface EventSchemaEnforcementManagerOptions {+ /** Retry transient schema-load failures (e.g. a Postgres pooler blip) instead of letting them propagate. */+ loaderRetry?: LoaderRetryOptions+}+export class EventSchemaEnforcementManager {private lazyLoader: LazyLoader<EventSchemaMap>- constructor(private postgres: PostgresRouter) {+ constructor(+ private postgres: PostgresRouter,+ options?: EventSchemaEnforcementManagerOptions+ ) {this.lazyLoader = new LazyLoader({name: 'EventSchemaEnforcementManager',refreshAgeMs: 2 * 60 * 1000, // 2 minutesrefreshJitterMs: 30 * 1000, // 30 seconds+ loaderRetry: options?.loaderRetry,loader: async (teamIds: string[]) => {return await this.fetchSchemas(teamIds)},diff --git a/nodejs/src/common/utils/lazy-loader.ts b/nodejs/src/common/utils/lazy-loader.tsindex e245f42c044a..369cae7996e5 100644--- a/nodejs/src/common/utils/lazy-loader.ts+++ b/nodejs/src/common/utils/lazy-loader.ts@@ -64,6 +64,16 @@ export type LoaderRetryOptions = {maxElapsedMs: number}+/**+ * Shared retry policy for loaders backed by transient-blip-prone dependencies (e.g. Postgres+ * behind PgBouncer). Sized to ride out a pooler restart without stalling callers for long.+ */+export const DEFAULT_LOADER_RETRY: LoaderRetryOptions = {+ retryIntervalMs: 250,+ retryJitterMs: 250,+ maxElapsedMs: 5000,+}+export type LazyLoaderOptions<T> = {name: string/** Function to load the values */diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex da0dfeb44cfc..c245ec492130 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -32,6 +32,7 @@ import {EventIngestionRestrictionManagerComponent,} from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'+import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { TeamManager } from '~/common/utils/team-manager'@@ -172,7 +173,11 @@ export class IngestionConsumer {staticForceOverflowTokens: this.tokenDistinctIdsToForceOverflow,})this.eventFilterManagerComponent = new EventFilterManagerComponent(deps.postgres)- this.eventSchemaEnforcementManager = new EventSchemaEnforcementManager(deps.postgres)+ // Schema loads run detached in the LazyLoader buffer, so an un-retried transient+ // failure can surface as an unhandled rejection and restart the worker.+ this.eventSchemaEnforcementManager = new EventSchemaEnforcementManager(deps.postgres, {+ loaderRetry: DEFAULT_LOADER_RETRY,+ })this.name = `ingestion-consumer-${this.topic}`diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.tsindex c3910d22be54..28b2e6759b67 100644--- a/nodejs/src/ingestion/pipelines/ai/consumer.ts+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts@@ -19,6 +19,7 @@ import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-persimport { PostgresRouter } from '~/common/utils/db/postgres'import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'+import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'import { TeamManager } from '~/common/utils/team-manager'import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'import { EventFilterManagerComponent } from '~/ingestion/common/event-filters'@@ -194,7 +195,11 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiSharedoverflowLaneTTLRefreshService: container.overflowLaneTTLRefreshService,concurrentBatches: config.INGESTION_WORKER_CONCURRENT_BATCHES,eventSchemaEnforcementEnabled: config.EVENT_SCHEMA_ENFORCEMENT_ENABLED,- eventSchemaEnforcementManager: new EventSchemaEnforcementManager(container.postgres),+ // Schema loads run detached in the LazyLoader buffer, so an un-retried transient+ // failure can surface as an unhandled rejection and restart the worker.+ eventSchemaEnforcementManager: new EventSchemaEnforcementManager(container.postgres, {+ loaderRetry: DEFAULT_LOADER_RETRY,+ }),topHog: container.topHog,aiBlobStore: container.aiBlobStore.store,aiBlobOffloadConfig,diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.tsindex 5b87ea72ef14..ab6f46bed52a 100644--- a/nodejs/src/servers/error-tracking-server.ts+++ b/nodejs/src/servers/error-tracking-server.ts@@ -14,6 +14,7 @@ import { ServerCommands } from '~/common/utils/commands'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { GeoIPService } from '~/common/utils/geoip'+import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { PubSub } from '~/common/utils/pubsub'import { TeamManager } from '~/common/utils/team-manager'@@ -161,7 +162,7 @@ export class ErrorTrackingServer implements NodeServer {this.pubsub = new PubSub(this.redisPool)await this.pubsub.start()- const teamManager = new TeamManager(this.postgres)+ const teamManager = new TeamManager(this.postgres, { loaderRetry: DEFAULT_LOADER_RETRY })// 2. Services needed by ErrorTrackingConsumer and HogTransformerconst geoipService = new GeoIPService(this.config.MMDB_FILE_LOCATION)@@ -215,7 +216,9 @@ export class ErrorTrackingServer implements NodeServer {outputs,teamManager,hogTransformer: createHogTransformerService(this.config, hogTransformerDeps),- groupTypeManager: new ReadOnlyGroupTypeManager(groupRepository),+ groupTypeManager: new ReadOnlyGroupTypeManager(groupRepository, {+ loaderRetry: DEFAULT_LOADER_RETRY,+ }),cookielessManager: this.cookielessManager!,redisPool: this.redisPool!,personRepository,diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 62c6ddda67be..4c1acd4957b4 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -20,6 +20,7 @@ import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'import { GeoIPService } from '~/common/utils/geoip'+import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { PubSub } from '~/common/utils/pubsub'@@ -236,7 +237,7 @@ export class IngestionApiServer implements NodeServer {this.pubsub = new PubSub(this.redisPool)await this.pubsub.start()- const teamManager = new TeamManager(this.postgres)+ const teamManager = new TeamManager(this.postgres, { loaderRetry: DEFAULT_LOADER_RETRY })// 2. Ingestion + CDP shared services (geoip, repos, encryption)const geoipService = new GeoIPService(this.config.MMDB_FILE_LOCATION)@@ -286,7 +287,9 @@ export class IngestionApiServer implements NodeServer {poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,})- const groupTypeManager = new GroupTypeManager(groupRepository, teamManager)+ const groupTypeManager = new GroupTypeManager(groupRepository, teamManager, {+ loaderRetry: DEFAULT_LOADER_RETRY,+ })// 4. Kafka producers for pipeline outputs (not consuming from Kafka)this.ingestionProducerRegistry = await createIngestionProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(@@ -418,7 +421,11 @@ export class IngestionApiServer implements NodeServer {aiSubpipelineFactory: createAiEventSubpipeline,eventFilterManager: eventFilterManagerStarted.value,eventIngestionRestrictionManager,- eventSchemaEnforcementManager: new EventSchemaEnforcementManager(this.postgres),+ // Schema loads run detached in the LazyLoader buffer, so an un-retried transient+ // failure can surface as an unhandled rejection and restart the worker.+ eventSchemaEnforcementManager: new EventSchemaEnforcementManager(this.postgres, {+ loaderRetry: DEFAULT_LOADER_RETRY,+ }),promiseScheduler: this.promiseScheduler,overflowRedirectService,overflowLaneTTLRefreshService,diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.tsindex e6d00e450e23..ca496a65ebc5 100644--- a/nodejs/src/servers/ingestion-general-server.ts+++ b/nodejs/src/servers/ingestion-general-server.ts@@ -22,6 +22,7 @@ import { ServerCommands } from '~/common/utils/commands'import { PostgresRouter, PostgresRouterComponent } from '~/common/utils/db/postgres'import { RedisPoolComponent } from '~/common/utils/db/redis'import { GeoIPService } from '~/common/utils/geoip'+import { DEFAULT_LOADER_RETRY } from '~/common/utils/lazy-loader'import { logger } from '~/common/utils/logger'import { PubSub } from '~/common/utils/pubsub'import { TeamManagerComponent } from '~/common/utils/team-manager'@@ -191,7 +192,7 @@ export class IngestionGeneralServer implements NodeServer {// ECONNREFUSED). The team loader runs detached in the LazyLoader buffer, so an un-retried// transient failure can surface as an unhandled rejection and restart the worker.new TeamManagerComponent(container.postgres, {- loaderRetry: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },+ loaderRetry: DEFAULT_LOADER_RETRY,})).add('cookielessManager', new CookielessManagerComponent(this.config, container.cookielessRedisPool))@@ -244,7 +245,7 @@ export class IngestionGeneralServer implements NodeServer {// detached in the LazyLoader buffer, so an un-retried transient failure can// surface as an unhandled rejection and restart the worker.const groupTypeManager = new GroupTypeManager(groupRepository, teamManager, {- loaderRetry: { retryIntervalMs: 250, retryJitterMs: 250, maxElapsedMs: 5000 },+ loaderRetry: DEFAULT_LOADER_RETRY,})const serviceLoaders: (() => Promise<PluginServerService>)[] = []