: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): retry the event batch when a team lookup fails (#100790)
Meikel Ratz79de426757e7
diff --git a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-events-consumer.test.tsindex 38c208e0dda7..953b39cb5106 100644--- a/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-events-consumer.test.ts@@ -4,6 +4,7 @@ import { mockProducerObserver } from '../../../tests/helpers/mocks/producer.mockimport { HogFlow } from '~/cdp/schema/hogflow'import { GroupReadRepository } from '~/common/groups/repositories/group-repository.interface'+import { DependencyUnavailableError } from '~/common/utils/db/error'import { closeHub, createHub } from '~/common/utils/db/hub'import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'@@ -116,6 +117,55 @@ describe('CdpEventsConsumer', () => {})})+ describe('parse failures', () => {+ beforeEach(async () => {+ await insertHogFunction({+ team_id: team.id,+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ })+ })++ it.each([+ [+ 'rethrows a retriable team lookup error so the batch is retried',+ new DependencyUnavailableError('connection reset', 'Postgres', new Error('reset')),+ true,+ ],+ ['drops the message on a non-retriable team lookup error', new Error('event shape is wrong'), false],+ ])('%s', async (_name, error, shouldRethrow) => {+ jest.spyOn(processor['deps'].teamManager, 'getTeam').mockRejectedValue(error)+ const messages = [createKafkaMessage(createIncomingEvent(team.id, {}))]++ if (shouldRethrow) {+ await expect(processor._parseKafkaBatch(messages)).rejects.toThrow(error)+ } else {+ await expect(processor._parseKafkaBatch(messages)).resolves.toEqual([])+ }+ })++ it('lets a retriable failure escape the batch handler, and processes the batch on a later attempt', async () => {+ // The consumer stores offsets only after this handler resolves, so the handler+ // rejecting is what leaves the batch unacknowledged. A try/catch added around+ // _parseKafkaBatch here would swallow the rejection and silently restore the old+ // drop-everything behaviour, which the unit assertion above cannot see.+ const error = new DependencyUnavailableError('connection reset', 'Postgres', new Error('reset'))+ const getTeam = jest.spyOn(processor['deps'].teamManager, 'getTeam').mockRejectedValue(error)+ const handleBatch = (processor['kafkaConsumer'].connect as jest.Mock).mock.calls[0][0]+ const messages = [createKafkaMessage(createIncomingEvent(team.id, {}))]++ await expect(handleBatch(messages)).rejects.toThrow(error)+ expect(mockQueueInvocations).not.toHaveBeenCalled()++ getTeam.mockRestore()+ const { backgroundTask } = await handleBatch(messages)+ await backgroundTask++ expect(mockQueueInvocations).toHaveBeenCalledWith([expect.objectContaining({ teamId: team.id })])+ })+ })+describe('general event processing', () => {describe('common processing', () => {let fnFetchNoFilters: HogFunctionTypediff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 210318c28b3a..ac9a28fa1636 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -182,6 +182,12 @@ export class CdpEventsConsumer<events.push(convertToHogFunctionInvocationGlobals(clickHouseEvent, team, this.config.SITE_URL))} catch (e) {+ // A dependency outage is not a poison message. Rethrowing fails the batch, so the+ // offsets stay put and the consumer retries, instead of dropping every event of a+ // team for the length of a Postgres blip.+ if (e?.isRetriable === true) {+ throw e+ }logger.error('Error parsing message', e)counterParseError.labels({ error: e.message }).inc()}diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex 7b3e09f2c94a..f10fde615926 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -199,6 +199,12 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {events.push(convertInternalEventToHogFunctionInvocationGlobals(event, team, this.config.SITE_URL))} catch (e) {+ // A dependency outage is not a poison message. Rethrowing fails the batch, so the+ // offsets stay put and the consumer retries, instead of dropping every event of a+ // team for the length of a Postgres blip.+ if (e?.isRetriable === true) {+ throw e+ }logger.error('Error parsing message', e)counterParseError.labels({ error: e.message }).inc()}diff --git a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.tsindex 06b33be92ac2..7cf1b5f36288 100644--- a/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-events-consumer.test.ts@@ -3,6 +3,7 @@ import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import '../../../tests/helpers/mocks/producer.mock'import { HogFlow } from '~/cdp/schema/hogflow'+import { DependencyUnavailableError } from '~/common/utils/db/error'import { closeHub, createHub } from '~/common/utils/db/hub'import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'@@ -88,6 +89,25 @@ describe('CDP Internal Events Consumer', () => {expect(events).toHaveLength(0)})+ it('should fail the batch when the team lookup hits a retriable error', async () => {+ const error = new DependencyUnavailableError('connection reset', 'Postgres', new Error('reset'))+ jest.spyOn(processor['deps'].teamManager, 'getTeam').mockRejectedValue(error)++ await expect(+ processor._parseKafkaBatch([createKafkaMessage(createInternalEvent(team.id, {}))])+ ).rejects.toThrow(error)+ })++ it('should let that failure escape the batch handler rather than swallowing it', async () => {+ // Offsets are stored only after the handler resolves, so the rejection reaching the+ // consumer is what leaves the batch unacknowledged.+ const error = new DependencyUnavailableError('connection reset', 'Postgres', new Error('reset'))+ jest.spyOn(processor['deps'].teamManager, 'getTeam').mockRejectedValue(error)+ const handleBatch = (processor['kafkaConsumer'].connect as jest.Mock).mock.calls[0][0]++ await expect(handleBatch([createKafkaMessage(createInternalEvent(team.id, {}))])).rejects.toThrow(error)+ })+describe('with an existing team and hog function', () => {beforeEach(async () => {await insertHogFunction({diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex 882cd0b5e1db..362409c07065 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -15,6 +15,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'@@ -474,7 +475,9 @@ export class PluginServer implements NodeServer {this.pubsub = new PubSub(this.redisPool)await this.pubsub.start()- const teamManager = new TeamManager(this.postgres)+ // The CDP consumers fail the batch on a retriable lookup error, so an un-absorbed blip+ // restarts the pod. The hog function and hog flow managers already retry in place.+ const teamManager = new TeamManager(this.postgres, { loaderRetry: DEFAULT_LOADER_RETRY })return { teamManager }}