: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): drain persons stores at shutdown before postgres closes (#113708)
José Sequeira765f1a028633
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.tsindex 8b36c23bc59f..b268c0e6aa3f 100644--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.test.ts@@ -1,7 +1,7 @@import { DateTime } from 'luxon'import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'-import { PERSONS_OUTPUT, PersonDistinctIdsOutput, PersonMergeEventsOutput, PersonsOutput } from '~/common/outputs'+import { PersonDistinctIdsOutput, PersonMergeEventsOutput, PersonsOutput } from '~/common/outputs'import {personProfileBatchIgnoredPropertiesCounter,personProfileBatchUpdateOutcomeCounter,@@ -3344,42 +3344,6 @@ describe('BatchWritingPersonStore', () => {cache.delete(`${teamId}:${person.id}`)})-- it('flushAndProduceMessages drains dirty entries and produces Kafka messages', async () => {- const cache = (personStore as any).personUpdateCache as Map<string, any>- cache.set(`${teamId}:${person.id}`, {- id: person.id,- uuid: person.uuid,- team_id: teamId,- distinct_id: 'test',- needs_write: true,- properties: person.properties,- properties_to_set: { new_prop: 'value' },- properties_to_unset: [],- version: person.version,- created_at: person.created_at,- is_identified: false,- is_user_id: null,- })-- const message = { output: PERSONS_OUTPUT, value: Buffer.from('{}') }- const flushSpy = jest- .spyOn(personStore, 'flush')- .mockResolvedValue([{ messages: [message], teamId, distinctId: 'test', uuid: person.uuid }])-- await personStore.flushAndProduceMessages()-- expect(flushSpy).toHaveBeenCalledTimes(1)- expect(mockIngestionWarningsOutputs.produce).toHaveBeenCalledTimes(1)- expect(mockIngestionWarningsOutputs.produce).toHaveBeenCalledWith(PERSONS_OUTPUT, {- key: null,- value: message.value,- teamId,- })-- // Remove injected entry so afterEach shutdown does not re-trigger a flush- cache.delete(`${teamId}:${person.id}`)- })})describe('releaseBatch', () => {diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.tsindex 1eabad18b2fa..64ffd517183e 100644--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts@@ -1572,28 +1572,6 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStorethis.personCache.resetMetrics()}- /**- * Flush all dirty entries and produce the resulting Kafka messages inline.- *- * Convenience wrapper for callers that don't run inside the pipeline's- * side-effect scheduler (e.g. server shutdown paths) and just need to drain- * buffered writes synchronously. Throws on the first produce failure.- */- async flushAndProduceMessages(): Promise<void> {- const flushResults = await this.flush()- await Promise.all(- flushResults.flatMap((record) =>- record.messages.map((message) =>- this.ingestionWarningsOutputs.produce(message.output, {- key: null,- value: message.value,- teamId: record.teamId,- })- )- )- )- }-/*** Stop the metric-emission timer and emit accumulated metrics. Idempotent.*diff --git a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.tsindex 393ccf87e37a..6a3a5a2c9c64 100644--- a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts@@ -139,8 +139,14 @@ function countFlushResultMessages(flushResults: { messages: unknown[] }[]): numb* These promises handle errors appropriately:* - MessageSizeTooLarge: Emits ingestion warning (non-fatal)* - Other errors: Propagated to fail the side effect+ *+ * Exported so the ingestion API server's shutdown drain can produce a bare+ * `flush()` result the same way the batch step does.*/-function createPersonProducePromises(personsStoreMessages: FlushResult[], outputs: PersonOutputs): Promise<unknown>[] {+export function createPersonProducePromises(+ personsStoreMessages: FlushResult[],+ outputs: PersonOutputs+): Promise<unknown>[] {const promises: Promise<unknown>[] = []for (const record of personsStoreMessages) {diff --git a/nodejs/src/servers/ingestion-api-server.test.ts b/nodejs/src/servers/ingestion-api-server.test.tsindex cc08d3be505a..6c09ba22ef0a 100644--- a/nodejs/src/servers/ingestion-api-server.test.ts+++ b/nodejs/src/servers/ingestion-api-server.test.ts@@ -1,7 +1,6 @@-import { GROUPS_OUTPUT } from '~/common/outputs'+import { GROUPS_OUTPUT, PERSONS_OUTPUT } from '~/common/outputs'import { GroupFlushResult } from '~/ingestion/common/groups/group-store.interface'-import { CleanupResources } from './base-server'import { IngestionApiServer } from './ingestion-api-server'describe('IngestionApiServer', () => {@@ -38,8 +37,7 @@ describe('IngestionApiServer', () => {;(server as any).groupStore = groupStore;(server as any).ingestionOutputs = ingestionOutputs- const cleanup: CleanupResources = (server as any).getCleanupResources()- await cleanup.additionalCleanup?.()+ await (server as any).drainStores()expect(ingestionOutputs.produce).toHaveBeenCalledWith(GROUPS_OUTPUT, {key: null,@@ -47,5 +45,51 @@ describe('IngestionApiServer', () => {teamId: flushResult.teamId,})})++ it('still drains the group store when the persons drain fails, and rethrows the failure', async () => {+ const personsStore = {+ flush: jest.fn().mockRejectedValue(new Error('persons flush failed')),+ shutdown: jest.fn().mockResolvedValue(undefined),+ }+ const groupStore = {+ flush: jest.fn().mockResolvedValue([]),+ shutdown: jest.fn().mockResolvedValue(undefined),+ }+ ;(server as any).pipelinePersonsStore = personsStore+ ;(server as any).groupStore = groupStore++ await expect((server as any).drainStores()).rejects.toThrow('persons flush failed')++ expect(groupStore.flush).toHaveBeenCalledTimes(1)+ expect(groupStore.shutdown).toHaveBeenCalledTimes(1)+ })++ // In shadow mode only the pipeline's store writes both backends; the raw store writes Postgres only.+ it('drains the pipeline persons store at shutdown and produces its messages, not the raw Postgres store', async () => {+ const message = { output: PERSONS_OUTPUT, value: Buffer.from('person-payload') }+ const personsStore = {+ flush: jest.fn().mockResolvedValue([]),+ shutdown: jest.fn().mockResolvedValue(undefined),+ }+ const pipelinePersonsStore = {+ flush: jest.fn().mockResolvedValue([{ messages: [message], teamId: 1, distinctId: 'd1', uuid: 'u1' }]),+ shutdown: jest.fn().mockResolvedValue(undefined),+ }+ const ingestionOutputs = { produce: jest.fn().mockResolvedValue(undefined) }+ ;(server as any).personsStore = personsStore+ ;(server as any).pipelinePersonsStore = pipelinePersonsStore+ ;(server as any).ingestionOutputs = ingestionOutputs++ await (server as any).drainStores()++ expect(pipelinePersonsStore.flush).toHaveBeenCalledTimes(1)+ expect(personsStore.flush).not.toHaveBeenCalled()+ expect(ingestionOutputs.produce).toHaveBeenCalledWith(PERSONS_OUTPUT, {+ key: null,+ value: message.value,+ teamId: 1,+ })+ expect(pipelinePersonsStore.shutdown).toHaveBeenCalledTimes(1)+ })})})diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex d4ce6800eb69..1d46329ee51d 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -48,6 +48,7 @@ import {import {FlushBatchStoresOutputs,createGroupProducePromises,+ createPersonProducePromises,} from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'import { TopHog } from '~/ingestion/framework/tophog'import {@@ -512,11 +513,17 @@ export class IngestionApiServer implements NodeServer {const service: PluginServerService = {id: 'ingestion-api',+ // Runs before the lifecycle ends Postgres and Redis, so in-flight batches and the store drain finish here.onShutdown: async () => {- await this.topHog.stop()- await this.hogTransformer.stop()- await eventFilterManagerStarted.stop()- await stopEventIngestionRestrictionManager()+ try {+ await this.grpcServer?.stop()+ await this.drainStores()+ } finally {+ await this.topHog.stop()+ await this.hogTransformer.stop()+ await eventFilterManagerStarted.stop()+ await stopEventIngestionRestrictionManager()+ }},healthcheck: () => this.isHealthy(),}@@ -531,6 +538,41 @@ export class IngestionApiServer implements NodeServer {return new HealthCheckResultOk()}+ /** Drains both stores even when one fails, then rethrows the first failure. */+ private async drainStores(): Promise<void> {+ const results = await Promise.allSettled([this.drainPersonsStore(), this.drainGroupStore()])+ this.personhogClientClosers.forEach((close) => close())+ const failed = results.find((result): result is PromiseRejectedResult => result.status === 'rejected')+ if (failed) {+ throw failed.reason+ }+ }++ private async drainPersonsStore(): Promise<void> {+ // In shadow mode the pipeline's store is the routing store, so both backends write the pending updates.+ const personsStore = this.pipelinePersonsStore ?? this.personsStore+ if (!personsStore) {+ return+ }+ const flushResults = await personsStore.flush()+ if (this.ingestionOutputs) {+ await Promise.all(createPersonProducePromises(flushResults, this.ingestionOutputs))+ }+ await personsStore.shutdown()+ }++ private async drainGroupStore(): Promise<void> {+ if (!this.groupStore) {+ return+ }+ const flushResults = await this.groupStore.flush()+ // flush() leaves the ClickHouse messages to the caller; skipping them would write Postgres only.+ if (flushResults.length > 0 && this.ingestionOutputs) {+ await Promise.all(createGroupProducePromises(flushResults, this.ingestionOutputs))+ }+ await this.groupStore.shutdown()+ }+private getCleanupResources(): CleanupResources {return {kafkaProducers: [],@@ -540,33 +582,8 @@ export class IngestionApiServer implements NodeServer {postgres: this.postgres,pubsub: this.pubsub,additionalCleanup: async () => {- // Stop accepting stream traffic before draining stores, so no- // new batches land mid-teardown.- await this.grpcServer?.stop()- // No Kafka offsets in this server — drain buffered writes before- // shutdown so shutdown() can assert a clean cache.- if (this.personsStore) {- await this.personsStore.flushAndProduceMessages()- }- if (this.pipelinePersonsStore) {- await this.pipelinePersonsStore.shutdown()- } else if (this.personsStore) {- await this.personsStore.shutdown()- }- this.personhogClientClosers.forEach((close) => close())- if (this.groupStore) {- const groupFlushResults = await this.groupStore.flush()- // flush() returns messages for the caller to produce (it no- // longer awaits ClickHouse delivery inline) — mirror- // personsStore.flushAndProduceMessages() so a drain at- // shutdown doesn't write Postgres but silently drop the- // corresponding ClickHouse row.- if (groupFlushResults.length > 0 && this.ingestionOutputs) {- await Promise.all(createGroupProducePromises(groupFlushResults, this.ingestionOutputs))- }- await this.groupStore.shutdown()- }this.cookielessManager?.shutdown()+ // Disconnected last: the store drain in the ingestion-api service's onShutdown produces through them.await this.ingestionProducerRegistry?.disconnectAll()},}