Skip to content

: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.

fix(ingestion): make person prefetch best-effort so it can't crash workers (#61441)

Paweł Ledwoń417699f49f55
diff --git a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts
index 9bd960456413..16a76c73afe4 100644
--- a/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/analytics/post-team-preprocessing-subpipeline.ts
@@ -97,13 +97,13 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
// Refresh TTLs for overflow lane events (keeps Redis flags alive)
.pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))
// Prefetch must run after cookieless, as cookieless changes distinct IDs.
- // Retry transient persons-Postgres failures (e.g. PgBouncer scale-down) instead
- // of letting them crash the consumer loop.
- .pipeBatchWithRetry(prefetchPersonsStep(personsStore, personsPrefetchEnabled), {
- tries: 3,
- sleepMs: 100,
- })
- // Batch insert personless distinct IDs after prefetch (uses prefetch cache)
+ // Prefetch is fire-and-forget (best-effort cache warming), so retry here would be a
+ // no-op — transient persons-Postgres failures are swallowed inside prefetchPersons so
+ // they can't surface as an unhandled rejection and crash the worker.
+ .pipeBatch(prefetchPersonsStep(personsStore, personsPrefetchEnabled))
+ // Batch insert personless distinct IDs after prefetch (uses prefetch cache).
+ // This step awaits its DB write, so retry transient persons-Postgres failures
+ // (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop.
.pipeBatchWithRetry(processPersonlessDistinctIdsBatchStep(personsStore, personsPrefetchEnabled), {
tries: 3,
sleepMs: 100,
diff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts
index c2c66e22ea95..4497c871daba 100644
--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts
+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.test.ts
@@ -4,7 +4,7 @@ import { INGESTION_WARNINGS_OUTPUT } from '~/ingestion/common/outputs'
import { IngestionOutputs } from '~/ingestion/outputs/ingestion-outputs'
import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
import { InternalPerson, TeamId } from '~/types'
-import { MessageSizeTooLarge } from '~/utils/db/error'
+import { DependencyUnavailableError, MessageSizeTooLarge } from '~/utils/db/error'
import { PostgresRouter } from '~/utils/db/postgres'
import { emitIngestionWarning } from '../../../ingestion/common/ingestion-warnings'
@@ -2652,5 +2652,89 @@ describe('BatchWritingPersonStore', () => {
expect(mockRepo.fetchPersonsByDistinctIds).toHaveBeenCalledTimes(1)
expect(mockRepo.fetchPerson).not.toHaveBeenCalled()
})
+
+ it('should resolve (not reject) on a transient persons-Postgres failure', async () => {
+ const personStoreForBatch = getPersonsStore()
+
+ mockRepo.fetchPersonsByDistinctIds.mockRejectedValueOnce(
+ new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('connect ECONNREFUSED'))
+ )
+
+ // Prefetch is fired without being awaited by its pipeline step, so a rejection here would
+ // surface as an unhandled rejection and crash the worker. It must resolve instead.
+ await expect(
+ personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])
+ ).resolves.toBeUndefined()
+
+ // Nothing should have been cached for the failed entry
+ expect(personStoreForBatch.getCheckCache().has(`${teamId}:user-1`)).toBe(false)
+ })
+
+ it('should rethrow an unexpected batch fetch failure rather than mask it', async () => {
+ const personStoreForBatch = getPersonsStore()
+
+ // A non-transient error (e.g. a broken query) must surface loudly, not be swallowed.
+ mockRepo.fetchPersonsByDistinctIds.mockRejectedValueOnce(new Error('something unexpected'))
+
+ await expect(personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])).rejects.toThrow(
+ 'something unexpected'
+ )
+ })
+
+ it('should let fetchForUpdate fall back to an on-demand fetch after a failed prefetch', async () => {
+ const personStoreForBatch = getPersonsStore()
+
+ mockRepo.fetchPersonsByDistinctIds.mockRejectedValueOnce(
+ new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('connect ECONNREFUSED'))
+ )
+
+ await personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])
+
+ // The failed prefetch left the caches empty, so fetchForUpdate must do its own fetch.
+ const result = await personStoreForBatch.fetchForUpdate(teamId, 'user-1')
+
+ expect(result).toEqual(person)
+ expect(mockRepo.fetchPerson).toHaveBeenCalledTimes(1)
+ })
+
+ it('should propagate a transient in-flight failure to fetchForChecking, not report the person absent', async () => {
+ const personStoreForBatch = getPersonsStore()
+
+ // Control when the batch fetch settles so fetchForChecking piggybacks on the in-flight prefetch.
+ let rejectFetch: (reason: Error) => void
+ const fetchPromise = new Promise<InternalPerson[]>((_resolve, reject) => {
+ rejectFetch = reject
+ })
+ mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(fetchPromise)
+
+ const prefetch = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])
+ const checking = personStoreForBatch.fetchForChecking(teamId, 'user-1')
+
+ rejectFetch!(new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('boom')))
+
+ // Must reject so the per-distinct-id pipeline retries — not resolve null ("person absent"),
+ // which would make processPersonlessStep create a fake person for an event that has a real one.
+ await expect(checking).rejects.toThrow('connect ECONNREFUSED')
+ // The fire-and-forget prefetch itself still recovers so it can't crash the worker.
+ await expect(prefetch).resolves.toBeUndefined()
+ })
+
+ it('should propagate a transient in-flight failure to fetchForUpdate rather than silently refetch', async () => {
+ const personStoreForBatch = getPersonsStore()
+
+ let rejectFetch: (reason: Error) => void
+ const fetchPromise = new Promise<InternalPerson[]>((_resolve, reject) => {
+ rejectFetch = reject
+ })
+ mockRepo.fetchPersonsByDistinctIds.mockReturnValueOnce(fetchPromise)
+
+ const prefetch = personStoreForBatch.prefetchPersons([{ teamId, distinctId: 'user-1' }])
+ const update = personStoreForBatch.fetchForUpdate(teamId, 'user-1')
+
+ rejectFetch!(new DependencyUnavailableError('connect ECONNREFUSED', 'Postgres', new Error('boom')))
+
+ await expect(update).rejects.toThrow('connect ECONNREFUSED')
+ await expect(prefetch).resolves.toBeUndefined()
+ })
})
})
diff --git a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts
index 91cc05b86367..8d09b8eff701 100644
--- a/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts
+++ b/nodejs/src/worker/ingestion/persons/batch-writing-person-store.ts
@@ -683,6 +683,14 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
return fetchPromise
}
+ /**
+ * Best-effort cache warmer for the given distinct IDs. Callers fire this without awaiting it,
+ * so its own rejection would become an unhandled rejection that exits the worker — so it swallows
+ * transient persons-Postgres unavailability (DependencyUnavailableError) here. The failure is not
+ * masked: each per-key promise (awaited by fetchForChecking/fetchForUpdate) still rejects, so a
+ * consumer propagates the error and the per-distinct-id pipeline retries it. Any other error
+ * (e.g. a broken query) is rethrown so it crashes loudly rather than being silently masked.
+ */
async prefetchPersons(teamDistinctIds: { teamId: number; distinctId: string }[]): Promise<void> {
if (teamDistinctIds.length === 0) {
return
@@ -755,16 +763,33 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
}
})
- // Register per-key promises so fetchForChecking/fetchForUpdate will wait on them
+ // Register per-key promises so fetchForChecking/fetchForUpdate can wait on the in-flight
+ // batch. On failure these reject, so a consumer propagates the error (and a transient
+ // DependencyUnavailableError is retried in the per-distinct-id pipeline) rather than seeing a
+ // misleading "person absent" null. The throwaway catch only marks the promise handled so an
+ // unconsumed key (its event may be dropped before the fetch) can't become an unhandled
+ // rejection — it does not change what awaiting consumers observe.
for (const { cacheKey } of uncachedEntries) {
- const keyPromise = batchFetchPromise.then((personsByKey) => {
- return personsByKey.get(cacheKey) ?? null
- })
+ const keyPromise = batchFetchPromise.then((personsByKey) => personsByKey.get(cacheKey) ?? null)
+ keyPromise.catch(() => {})
this.fetchPromisesForChecking.set(cacheKey, keyPromise)
}
- // Await the batch fetch so callers who await prefetchPersons() get blocking behavior
- await batchFetchPromise
+ // Recover from a retriable failure (e.g. transient persons-Postgres unavailability) so this
+ // best-effort, fire-and-forget warmer can't crash the worker. The failure is not masked:
+ // consumers still observe the rejection on their per-key promise and retry it in the
+ // per-distinct-id pipeline — we only swallow the redundant fire-and-forget copy. We recover
+ // only on an explicit `isRetriable === true`, not the pipeline's `!== false`: an unflagged
+ // error (e.g. a broken query) should rethrow and crash loudly rather than be silently masked.
+ await batchFetchPromise.catch((error) => {
+ if (error?.isRetriable === true) {
+ logger.warn('⚠️', 'prefetchPersons failed on a retriable persons-Postgres error', {
+ error: String(error),
+ })
+ return
+ }
+ throw error
+ })
}
async fetchForUpdate(teamId: Team['id'], distinctId: string): Promise<InternalPerson | null> {