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.

feat(ingestion): prefetch team, schema, and hog function caches per chunk (#91892)

José Sequeiraa1b395747a12
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
index ec3b26f53339..cb55a8c53f35 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.test.ts
@@ -90,6 +90,28 @@ describe('HogTransformer', () => {
await transformer.stop()
})
+ it('prefetchHogFunctionsForTeams leaves the transformation caches warm for the event path', async () => {
+ const fn = createHogFunction({
+ type: 'transformation',
+ name: defaultTemplate.name,
+ team_id: teamId,
+ enabled: true,
+ bytecode: await compileHog(defaultTemplate.code),
+ })
+ await insertHogFunction(hub.postgres, teamId, fn)
+
+ await hogTransformer.prefetchHogFunctionsForTeams([teamId])
+
+ const querySpy = jest.spyOn(hub.postgres, 'query')
+ const result = await hogTransformer.transformEventAndProduceMessages(createPluginEvent({}, teamId))
+
+ expect(result.invocationResults).toHaveLength(1)
+ const hogFunctionQueries = querySpy.mock.calls
+ .map((call) => call[3])
+ .filter((tag) => tag === 'fetchAllTeamHogFunctions' || tag === 'fetchHogFunctions')
+ expect(hogFunctionQueries).toEqual([])
+ })
+
describe('transformEvent', () => {
it('handles geoip lookup transformation', async () => {
// Setup the hog function
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index b6cd338b17d6..686c4d33bc20 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -102,6 +102,15 @@ export class HogTransformerService implements HogTransformer {
await this.hogFunctionMonitoringService.flush()
}
+ public async prefetchHogFunctionsForTeams(teamIds: number[]): Promise<void> {
+ // Warm the by-team and by-id loaders directly, skipping the per-team assembly and sort
+ // that getHogFunctionsForTeams would do and the event path redoes anyway.
+ const idsByTeam = await this.hogFunctionManager.getHogFunctionIdsForTeams(teamIds, ['transformation'], {
+ flush: true,
+ })
+ await this.hogFunctionManager.getHogFunctions(Object.values(idsByTeam).flat(), { flush: true })
+ }
+
private async getTransformationFunctions() {
if (!this.cachedTransformationFunctions) {
this.cachedGeoIp = await this.geoipService.get()
diff --git a/nodejs/src/cdp/services/managers/hog-function-manager.service.ts b/nodejs/src/cdp/services/managers/hog-function-manager.service.ts
index c9d8433850e1..a54628e5a471 100644
--- a/nodejs/src/cdp/services/managers/hog-function-manager.service.ts
+++ b/nodejs/src/cdp/services/managers/hog-function-manager.service.ts
@@ -1,6 +1,6 @@
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, LoadOptions } from '~/common/utils/lazy-loader'
import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
import { PubSub } from '~/common/utils/pubsub'
@@ -75,11 +75,13 @@ export class HogFunctionManagerService {
this.lazyLoaderByTeam = new LazyLoader({
name: 'hog_function_manager_by_team',
loader: async (teamIds) => await this.fetchTeamHogFunctions(teamIds),
+ loaderRetry: DEFAULT_LOADER_RETRY,
})
this.lazyLoader = new LazyLoader({
name: 'hog_function_manager',
loader: async (ids) => await this.fetchHogFunctions(ids),
+ loaderRetry: DEFAULT_LOADER_RETRY,
})
this.pubSub.on<{ teamId: Team['id']; hogFunctionIds: HogFunctionType['id'][] }>(
@@ -126,14 +128,18 @@ export class HogFunctionManagerService {
public async getHogFunctionIdsForTeams(
teamIds: Team['id'][],
- types: HogFunctionTypeType[]
+ types: HogFunctionTypeType[],
+ options?: LoadOptions
): Promise<Record<Team['id'], string[]>> {
const result = teamIds.reduce<Record<Team['id'], string[]>>((acc, teamId) => {
acc[teamId] = []
return acc
}, {})
- const teamHogFunctions = await this.lazyLoaderByTeam.getMany(teamIds.map((x) => x.toString()))
+ const teamHogFunctions = await this.lazyLoaderByTeam.getMany(
+ teamIds.map((x) => x.toString()),
+ options
+ )
if (!teamHogFunctions) {
return result
@@ -158,9 +164,10 @@ export class HogFunctionManagerService {
}
public async getHogFunctions(
- ids: HogFunctionType['id'][]
+ ids: HogFunctionType['id'][],
+ options?: LoadOptions
): Promise<Record<HogFunctionType['id'], HogFunctionType | null>> {
- return await this.lazyLoader.getMany(ids)
+ return await this.lazyLoader.getMany(ids, options)
}
public async fetchHogFunction(id: HogFunctionType['id']): Promise<HogFunctionType | null> {
diff --git a/nodejs/src/common/hog-transformations/hog-transformer.interface.ts b/nodejs/src/common/hog-transformations/hog-transformer.interface.ts
index 8df986ac9855..f6c70931ba68 100644
--- a/nodejs/src/common/hog-transformations/hog-transformer.interface.ts
+++ b/nodejs/src/common/hog-transformations/hog-transformer.interface.ts
@@ -23,4 +23,5 @@ export interface HogTransformer {
transformEventAndProduceMessages(event: PluginEvent): Promise<HogTransformationResult>
// Refresh cached transformation hog-function states for the given teams (used by the ingestion
// prefetch step). Encapsulates the hog-function-manager lookup ingestion would otherwise reach into.
+ prefetchHogFunctionsForTeams(teamIds: number[]): Promise<void>
}
diff --git a/nodejs/src/common/tracing/tracing-utils.ts b/nodejs/src/common/tracing/tracing-utils.ts
index 35156fa32f32..2112ff333274 100644
--- a/nodejs/src/common/tracing/tracing-utils.ts
+++ b/nodejs/src/common/tracing/tracing-utils.ts
@@ -105,6 +105,8 @@ interface FunctionInstrumentationOptions {
logExecutionTime?: boolean
sendException?: boolean
measureTime?: boolean
+ /** Stamped as the `tag` attribute on the span and the summary metric, to tell apart callers sharing a key. */
+ tag?: string
}
/**
@@ -123,6 +125,7 @@ export async function instrumentFn<T>(
const sendException = (typeof options === 'string' ? undefined : options.sendException) ?? true
const logExecutionTime = (typeof options === 'string' ? undefined : options.logExecutionTime) ?? false
const measureTime = (typeof options === 'string' ? undefined : options.measureTime) ?? true
+ const tag = typeof options === 'string' ? undefined : options.tag
const t = timeoutGuard(timeoutMessage, getLoggingContext, timeout, sendException, () => {
instrumentedFunctionTimeout.labels({ function: key }).inc()
@@ -134,7 +137,7 @@ export async function instrumentFn<T>(
// Skip expensive span creation when tracing is disabled
const result = defaultConfig.DISABLE_OPENTELEMETRY_TRACING
? await func()
- : await withSpan('instrumented_function', key, {}, func)
+ : await withSpan('instrumented_function', key, tag ? { tag } : {}, func)
end?.({ success: 'true' })
if (logExecutionTime) {
logTime(startTime, key)
diff --git a/nodejs/src/common/utils/event-schema-enforcement-manager.ts b/nodejs/src/common/utils/event-schema-enforcement-manager.ts
index f6543c155992..e34803fc2047 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, LoaderRetryOptions } from './lazy-loader'
+import { LazyLoader, LoadOptions, LoaderRetryOptions } from './lazy-loader'
/**
* Raw row from the database query - one row per property per event.
@@ -57,8 +57,8 @@ export class EventSchemaEnforcementManager {
/**
* Get enforced event schemas for multiple teams.
*/
- public async getSchemasForTeams(teamIds: number[]): Promise<Record<string, EventSchemaMap>> {
- const results = await this.lazyLoader.getMany(teamIds.map(String))
+ public async getSchemasForTeams(teamIds: number[], options?: LoadOptions): Promise<Record<string, EventSchemaMap>> {
+ const results = await this.lazyLoader.getMany(teamIds.map(String), options)
const converted: Record<string, EventSchemaMap> = {}
for (const [key, value] of Object.entries(results)) {
converted[key] = value ?? new Map()
diff --git a/nodejs/src/common/utils/lazy-loader.test.ts b/nodejs/src/common/utils/lazy-loader.test.ts
index 9ddb13e04752..12ca48b8700c 100644
--- a/nodejs/src/common/utils/lazy-loader.test.ts
+++ b/nodejs/src/common/utils/lazy-loader.test.ts
@@ -133,6 +133,26 @@ describe('LazyLoader', () => {
})
})
+ describe('getMany with flush', () => {
+ it('issues the buffered load at once, carrying keys already buffered, and later gets join it', async () => {
+ const slowBufferLoader = new LazyLoader<string>({ name: 'test', loader, bufferMs: 5000 })
+ loader.mockImplementation(async (keys: string[]) => {
+ await delay(20)
+ return Object.fromEntries(keys.map((key) => [key, { val: key }]))
+ })
+
+ const buffered = slowBufferLoader.get('key1')
+ const flushed = slowBufferLoader.getMany(['key2'], { flush: true })
+ const joined = slowBufferLoader.get('key1')
+
+ const results = await Promise.all([buffered, flushed, joined])
+
+ expect(loader).toHaveBeenCalledTimes(1)
+ expect(loader).toHaveBeenCalledWith(['key1', 'key2'])
+ expect(results).toEqual([{ val: 'key1' }, { key2: { val: 'key2' } }, { val: 'key1' }])
+ })
+ })
+
describe('getMany', () => {
it('loads and caches multiple values', async () => {
loader.mockResolvedValue({ key1: 'value1', key2: 'value2' })
diff --git a/nodejs/src/common/utils/lazy-loader.ts b/nodejs/src/common/utils/lazy-loader.ts
index 369cae7996e5..05a5c06374cf 100644
--- a/nodejs/src/common/utils/lazy-loader.ts
+++ b/nodejs/src/common/utils/lazy-loader.ts
@@ -94,6 +94,14 @@ export type LazyLoaderOptions<T> = {
maxSize?: number
}
+export type LoadOptions = {
+ /**
+ * Issue the buffered load now instead of waiting out `bufferMs`. For a caller that already
+ * holds the whole batch, such as a chunk prefetch, the buffer only delays the query.
+ */
+ flush?: boolean
+}
+
type LazyLoaderMap<T> = Record<string, T | null | undefined>
/**
@@ -125,6 +133,8 @@ export class LazyLoader<T> {
| {
keys: Set<string>
promise: Promise<void>
+ /** Fires the buffered load now; a no-op once the buffer timer has fired. */
+ flush: () => void
}
| undefined
@@ -162,8 +172,8 @@ export class LazyLoader<T> {
return loaded[key] ?? null
}
- public async getMany(keys: string[]): Promise<Record<string, T | null>> {
- return await this.loadViaCache(keys)
+ public async getMany(keys: string[], options?: LoadOptions): Promise<Record<string, T | null>> {
+ return await this.loadViaCache(keys, options)
}
public markForRefresh(key: string | string[]): void {
@@ -215,8 +225,8 @@ export class LazyLoader<T> {
* If not cached, the value is loaded as part of the batch and added to the cache.
* If the value is older than the refreshAge, it is loaded from the database.
*/
- private async loadViaCache(keys: string[]): Promise<Record<string, T | null>> {
- return await instrumentFn(`lazyLoader.loadViaCache`, async () => {
+ private async loadViaCache(keys: string[], options?: LoadOptions): Promise<Record<string, T | null>> {
+ return await instrumentFn({ key: `lazyLoader.loadViaCache`, tag: this.options.name }, async () => {
// No prototype, for the same reason as the cache: keys are caller-supplied, and this
// object is handed back to callers who may iterate or spread it.
const results: Record<string, T | null> = Object.create(null)
@@ -268,7 +278,7 @@ export class LazyLoader<T> {
lazyLoaderFullCacheHits.labels({ name: this.options.name, hit: 'miss' }).inc()
// We have something to load so we schedule it and then await all of them
- await this.load(Array.from(keysToLoad))
+ await this.load(Array.from(keysToLoad), options)
for (const key of keys) {
// Grab the new cached result for all keys
@@ -285,7 +295,7 @@ export class LazyLoader<T> {
*
* Loaded values land in `this.cache` via `setValues`; callers read them back from there.
*/
- private async load(keys: string[]): Promise<void> {
+ private async load(keys: string[], options?: LoadOptions): Promise<void> {
const bufferMs = this.options.bufferMs ?? defaultConfig.LAZY_LOADER_DEFAULT_BUFFER_MS
const keyPromises: Promise<void>[] = []
@@ -300,21 +310,7 @@ export class LazyLoader<T> {
lazyLoaderQueuedCacheHits.labels({ name: this.options.name, hit: 'miss' }).inc()
if (!this.buffer) {
- // If we don't have a buffer then we create one
- // The buffer is a combination of a set of keys and a promise that will resolve after a setTimeout to then call the loader for those keys
- this.buffer = {
- keys: new Set(),
- promise: new Promise<string[]>((resolve) => {
- setTimeout(() => {
- const keys = Array.from(this.buffer!.keys)
- this.buffer = undefined
- resolve(keys)
- }, bufferMs)
- }).then(async (bufferedKeys) => {
- logger.debug('[LazyLoader]', this.options.name, 'Loading: ', bufferedKeys)
- this.setValues(await this.invokeLoader(bufferedKeys))
- }),
- }
+ this.buffer = this.createBuffer(bufferMs)
lazyLoaderBufferUsage.labels({ name: this.options.name, hit: 'miss' }).inc()
} else {
lazyLoaderBufferUsage.labels({ name: this.options.name, hit: 'hit' }).inc()
@@ -330,9 +326,42 @@ export class LazyLoader<T> {
keyPromises.push(pendingLoad)
}
+ if (options?.flush) {
+ // Keys other callers buffered meanwhile ride along; they only get served sooner.
+ this.buffer?.flush()
+ }
+
await Promise.all(keyPromises)
}
+ /**
+ * A buffer collects keys until its timer fires, or until `flush` fires it early, then calls
+ * the loader once for all of them. Whichever fires first wins; the other is a no-op.
+ */
+ private createBuffer(bufferMs: number): NonNullable<typeof this.buffer> {
+ const keys = new Set<string>()
+ let fired = false
+ let fire: () => void = () => {}
+
+ const promise = new Promise<string[]>((resolve) => {
+ const timer = setTimeout(() => fire(), bufferMs)
+ fire = () => {
+ if (fired) {
+ return
+ }
+ fired = true
+ clearTimeout(timer)
+ this.buffer = undefined
+ resolve(Array.from(keys))
+ }
+ }).then(async (bufferedKeys) => {
+ logger.debug('[LazyLoader]', this.options.name, 'Loading: ', bufferedKeys)
+ this.setValues(await this.invokeLoader(bufferedKeys))
+ })
+
+ return { keys, promise, flush: () => fire() }
+ }
+
/**
* Invoke the loader and normalize its result into a map this class owns: no prototype, an entry
* for every requested key, and `undefined` collapsed to `null`. Keys the loader returns beyond
diff --git a/nodejs/src/common/utils/team-manager.ts b/nodejs/src/common/utils/team-manager.ts
index f6d85854918f..003b729b5095 100644
--- a/nodejs/src/common/utils/team-manager.ts
+++ b/nodejs/src/common/utils/team-manager.ts
@@ -2,7 +2,7 @@ import { Properties } from '~/plugin-scaffold'
import { OrganizationAvailableFeature, ProjectId, Team } from '~/types'
import { PostgresRouter, PostgresUse } from './db/postgres'
-import { LazyLoader, LoaderRetryOptions } from './lazy-loader'
+import { LazyLoader, LoadOptions, LoaderRetryOptions } from './lazy-loader'
import { logger } from './logger'
import { captureTeamEvent } from './posthog'
@@ -50,8 +50,8 @@ export class TeamManager {
return this.lazyLoader.getMany(teamIds.map(String))
}
- public async getTeamsByTokens(tokens: string[]): Promise<Record<string, Team | null>> {
- return this.lazyLoader.getMany(tokens)
+ public async getTeamsByTokens(tokens: string[], options?: LoadOptions): Promise<Record<string, Team | null>> {
+ return this.lazyLoader.getMany(tokens, options)
}
public async hasAvailableFeature(teamId: number, feature: OrganizationAvailableFeature): Promise<boolean> {
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index 272faa1f2405..3d435656d254 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -210,6 +210,12 @@ export type IngestionConsumerConfig = {
GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: number
GROUPS_PREFETCH_ENABLED: boolean
+ // Team-keyed cache prefetch config: one batched warm-up per chunk for each cache,
+ // instead of a per-event lookup in the sequential steps that read it.
+ TEAMS_PREFETCH_ENABLED: boolean
+ EVENT_SCHEMAS_PREFETCH_ENABLED: boolean
+ HOG_FUNCTIONS_PREFETCH_ENABLED: boolean
+
// Event overflow config
EVENT_OVERFLOW_BUCKET_CAPACITY: number
EVENT_OVERFLOW_BUCKET_REPLENISH_RATE: number
@@ -369,6 +375,10 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: 50,
GROUPS_PREFETCH_ENABLED: false,
+ TEAMS_PREFETCH_ENABLED: false,
+ EVENT_SCHEMAS_PREFETCH_ENABLED: false,
+ HOG_FUNCTIONS_PREFETCH_ENABLED: false,
+
// Event overflow config
EVENT_OVERFLOW_BUCKET_CAPACITY: 1000,
EVENT_OVERFLOW_BUCKET_REPLENISH_RATE: 1.0,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index c64805f30668..e31a0439d5e6 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -295,6 +295,9 @@ export class IngestionConsumer {
preservePartitionLocality: this.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
groupsPrefetchEnabled: this.config.GROUPS_PREFETCH_ENABLED,
+ teamsPrefetchEnabled: this.config.TEAMS_PREFETCH_ENABLED,
+ eventSchemasPrefetchEnabled: this.config.EVENT_SCHEMAS_PREFETCH_ENABLED,
+ hogFunctionsPrefetchEnabled: this.config.HOG_FUNCTIONS_PREFETCH_ENABLED,
outputs,
perDistinctIdOptions: {
SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: this.config.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP,
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 4e74fe87b049..c00026e23d1f 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -54,6 +54,7 @@ import {
PostTeamPreprocessingSubpipelineConfig,
createPostTeamPreprocessingSubpipeline,
} from './post-team-preprocessing-subpipeline'
+import { prefetchTeamsStep } from './steps/prefetchTeamsStep'
export interface JoinedIngestionPipelineConfig {
eventSchemaEnforcementEnabled: boolean
@@ -61,6 +62,9 @@ export interface JoinedIngestionPipelineConfig {
preservePartitionLocality: boolean
personsPrefetchEnabled: boolean
groupsPrefetchEnabled: boolean
+ teamsPrefetchEnabled: boolean
+ eventSchemasPrefetchEnabled: boolean
+ hogFunctionsPrefetchEnabled: boolean
outputs: IngestionOutputs<
| EventOutput
| FlagEvaluationsOutput
@@ -128,6 +132,9 @@ export function createJoinedIngestionPipeline<
preservePartitionLocality,
personsPrefetchEnabled,
groupsPrefetchEnabled,
+ teamsPrefetchEnabled,
+ eventSchemasPrefetchEnabled,
+ hogFunctionsPrefetchEnabled,
outputs,
perDistinctIdOptions,
concurrentBatches,
@@ -166,7 +173,10 @@ export function createJoinedIngestionPipeline<
featureFlagCalledDedupService,
personsPrefetchEnabled,
groupsPrefetchEnabled,
+ eventSchemasPrefetchEnabled,
+ hogFunctionsPrefetchEnabled,
groupTypeManager,
+ hogTransformer,
}
const perEventConfig: EventSubpipelineConfig = {
@@ -217,6 +227,10 @@ export function createJoinedIngestionPipeline<
// handled by the matching only-cookieless step in post-team, which keys on
// the hashed distinct_id assigned by the cookieless step.
.pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))
+ // Warm the team cache for the chunk's tokens in one batched load while message
+ // bodies parse, so the per-event lookups in resolveTeam hit cache or coalesce
+ // onto the in-flight load instead of paying a serial load per token.
+ .pipeChunk(prefetchTeamsStep(teamManager, teamsPrefetchEnabled))
.parseMessage()
.resolveTeam()
.pipe(createValidateHistoricalMigrationStep())
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index d55a827d7037..7bf3892bdaa3 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -1,6 +1,7 @@
import { Message } from 'node-rdkafka'
import { GroupTypeManager } from '~/common/groups/group-type-manager'
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'
@@ -23,7 +24,9 @@ import {
} from '~/ingestion/common/steps/event-preprocessing'
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
+import { prefetchEventSchemasStep } from '~/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep'
import { prefetchGroupsStep } from '~/ingestion/pipelines/analytics/steps/prefetchGroupsStep'
+import { prefetchHogFunctionsStep } from '~/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep'
import { prefetchPersonsStep } from '~/ingestion/pipelines/analytics/steps/prefetchPersonsStep'
import { PluginEvent } from '~/plugin-scaffold'
import { EventHeaders, Team } from '~/types'
@@ -50,7 +53,10 @@ export interface PostTeamPreprocessingSubpipelineConfig {
featureFlagCalledDedupService?: FeatureFlagCalledDedupService
personsPrefetchEnabled: boolean
groupsPrefetchEnabled: boolean
+ eventSchemasPrefetchEnabled: boolean
+ hogFunctionsPrefetchEnabled: boolean
groupTypeManager: GroupTypeManager
+ hogTransformer: HogTransformer
}
export function createPostTeamPreprocessingSubpipeline<
@@ -75,11 +81,23 @@ export function createPostTeamPreprocessingSubpipeline<
featureFlagCalledDedupService,
personsPrefetchEnabled,
groupsPrefetchEnabled,
+ eventSchemasPrefetchEnabled,
+ hogFunctionsPrefetchEnabled,
groupTypeManager,
+ hogTransformer,
} = config
return (
builder
+ // Warm the schema cache with one batched load per chunk before the sequential chain
+ // below reads it one event at a time. The prefetch shares the enforcement flag,
+ // matching when the validation step reads the cache.
+ .pipeChunk(
+ prefetchEventSchemasStep(
+ eventSchemaEnforcementManager,
+ eventSchemasPrefetchEnabled && eventSchemaEnforcementEnabled
+ )
+ )
// These validation steps are synchronous, so we can process events sequentially.
.sequentially((b) =>
b
@@ -115,5 +133,9 @@ export function createPostTeamPreprocessingSubpipeline<
// Same best-effort, fire-and-forget cache warming for groups: one
// batched fetch for the chunk's $groupidentify group keys.
.pipeChunk(prefetchGroupsStep(groupTypeManager, groupsPrefetchEnabled))
+ // Warm the transformation hog-function cache last, after the drop steps above, so
+ // only teams with surviving events are loaded. The transformer runs much later in
+ // the event subpipeline, so the load still lands well ahead of its reads.
+ .pipeChunk(prefetchHogFunctionsStep(hogTransformer, hogFunctionsPrefetchEnabled))
)
}
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/createPrefetchStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/createPrefetchStep.test.ts
new file mode 100644
index 000000000000..955ba6f1bbc6
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/createPrefetchStep.test.ts
@@ -0,0 +1,63 @@
+import { logger } from '~/common/utils/logger'
+import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'
+import { createPrefetchStep } from '~/ingestion/pipelines/analytics/steps/createPrefetchStep'
+
+type TestInput = { key: string | null }
+
+const flushRejections = () => new Promise((resolve) => setImmediate(resolve))
+
+describe('createPrefetchStep', () => {
+ let load: jest.Mock<Promise<unknown>, [string[]]>
+
+ const createStep = (enabled = true) =>
+ createPrefetchStep<TestInput, string>({
+ name: 'prefetchTestStep',
+ extractKey: (event) => event.key,
+ load,
+ enabled,
+ })
+
+ beforeEach(() => {
+ load = jest.fn().mockResolvedValue({})
+ })
+
+ it('stamps the given name on the step for framework attribution', () => {
+ expect(createStep().name).toBe('prefetchTestStep')
+ })
+
+ it('loads each distinct key once, skips events without a key, and passes every event through', async () => {
+ const events: TestInput[] = [{ key: 'a' }, { key: 'b' }, { key: 'a' }, { key: null }]
+
+ const results = await createStep()(events)
+
+ expect(results.map((result) => result.type)).toEqual(Array(4).fill(PipelineResultType.OK))
+ expect(results.filter(isOkResult).map((result) => result.value)).toEqual(events)
+ expect(load).toHaveBeenCalledTimes(1)
+ expect(load).toHaveBeenCalledWith(['a', 'b'])
+ })
+
+ it.each([
+ ['disabled', false, [{ key: 'a' }]],
+ ['no event has a key', true, [{ key: null }]],
+ ['the chunk is empty', true, []],
+ ])('does not load when %s', async (_case, enabled, events: TestInput[]) => {
+ const results = await createStep(enabled)(events)
+
+ expect(results.map((result) => result.type)).toEqual(Array(events.length).fill(PipelineResultType.OK))
+ expect(load).not.toHaveBeenCalled()
+ })
+
+ it('keeps events flowing and warns when the load fails on a retriable error', async () => {
+ load.mockRejectedValue(Object.assign(new Error('postgres down'), { isRetriable: true }))
+
+ const results = await createStep()([{ key: 'a' }])
+ await flushRejections()
+
+ expect(results.map((result) => result.type)).toEqual([PipelineResultType.OK])
+ expect(logger.warn).toHaveBeenCalledWith(
+ '⚠️',
+ 'prefetchTestStep failed on a retriable error',
+ expect.objectContaining({ error: expect.stringContaining('postgres down') })
+ )
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/createPrefetchStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/createPrefetchStep.ts
new file mode 100644
index 000000000000..7eacf834d487
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/createPrefetchStep.ts
@@ -0,0 +1,52 @@
+import { logger } from '~/common/utils/logger'
+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'
+import { ok } from '~/ingestion/framework/results'
+
+export interface PrefetchStepOptions<T, K> {
+ /** Stamped as the step's function name, which the framework uses for error attribution and metrics. */
+ name: string
+ /** Key to warm for an event. Return null to skip the event. */
+ extractKey: (event: T) => K | null
+ /** Batched load for the chunk's distinct keys. The result is discarded; the cache keeps it. */
+ load: (keys: K[]) => Promise<unknown>
+ enabled: boolean
+}
+
+/**
+ * Builds a chunk step that warms a lazy-loader cache for all distinct keys in the
+ * chunk with one batched load, instead of a single-key fetch per event when a later
+ * sequential step reads the cache. Fire-and-forget: the lazy loader coalesces the
+ * per-event lookups issued while this load is in flight onto the same promise, so
+ * they fail together with it and the reading step handles the error. The catch only
+ * keeps the discarded copy of the rejection from becoming an unhandled rejection.
+ */
+export function createPrefetchStep<T, K>(options: PrefetchStepOptions<T, K>): ChunkProcessingStep<T, T> {
+ const { name, extractKey, load, enabled } = options
+
+ const step: ChunkProcessingStep<T, T> = (events) => {
+ if (enabled && events.length > 0) {
+ const keys = new Set<K>()
+ for (const event of events) {
+ const key = extractKey(event)
+ if (key !== null) {
+ keys.add(key)
+ }
+ }
+ if (keys.size > 0) {
+ void load([...keys]).catch((error) => {
+ // Recover only on an explicit retriable error. An unflagged error, such as a
+ // broken query, rethrows and crashes loudly rather than being masked.
+ if (error?.isRetriable === true) {
+ logger.warn('⚠️', `${name} failed on a retriable error`, { error: String(error) })
+ return
+ }
+ throw error
+ })
+ }
+ }
+ return Promise.resolve(events.map((event) => ok(event)))
+ }
+
+ Object.defineProperty(step, 'name', { value: name })
+ return step
+}
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep.test.ts
new file mode 100644
index 000000000000..0e29cd2fe81b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep.test.ts
@@ -0,0 +1,20 @@
+import { PipelineResultType } from '~/ingestion/framework/results'
+import { prefetchEventSchemasStep } from '~/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep'
+
+type TestInput = { team: { id: number } }
+
+function createInput(teamId: number): TestInput {
+ return { team: { id: teamId } }
+}
+
+describe('prefetchEventSchemasStep', () => {
+ it('warms the schema cache by team id', async () => {
+ const manager = { getSchemasForTeams: jest.fn().mockResolvedValue({}) }
+ const step = prefetchEventSchemasStep<TestInput>(manager, true)
+
+ const results = await step([createInput(3), createInput(4)])
+
+ expect(results.map((result) => result.type)).toEqual(Array(2).fill(PipelineResultType.OK))
+ expect(manager.getSchemasForTeams).toHaveBeenCalledWith([3, 4], { flush: true })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep.ts
new file mode 100644
index 000000000000..3a905ee0881f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchEventSchemasStep.ts
@@ -0,0 +1,18 @@
+import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
+import { createPrefetchStep } from '~/ingestion/pipelines/analytics/steps/createPrefetchStep'
+import { Team } from '~/types'
+
+type PrefetchEventSchemasStepInput = { team: Pick<Team, 'id'> }
+
+/** Warms the enforced-schema cache for the chunk's teams ahead of validateEventSchemaStep's per-event lookups. */
+export function prefetchEventSchemasStep<T extends PrefetchEventSchemasStepInput>(
+ eventSchemaEnforcementManager: Pick<EventSchemaEnforcementManager, 'getSchemasForTeams'>,
+ enabled: boolean
+) {
+ return createPrefetchStep<T, number>({
+ name: 'prefetchEventSchemasStep',
+ extractKey: (event) => event.team.id,
+ load: (teamIds) => eventSchemaEnforcementManager.getSchemasForTeams(teamIds, { flush: true }),
+ enabled,
+ })
+}
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep.test.ts
new file mode 100644
index 000000000000..fb6fb889dd14
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep.test.ts
@@ -0,0 +1,20 @@
+import { PipelineResultType } from '~/ingestion/framework/results'
+import { prefetchHogFunctionsStep } from '~/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep'
+
+type TestInput = { team: { id: number } }
+
+function createInput(teamId: number): TestInput {
+ return { team: { id: teamId } }
+}
+
+describe('prefetchHogFunctionsStep', () => {
+ it('warms the hog function cache by team id', async () => {
+ const hogTransformer = { prefetchHogFunctionsForTeams: jest.fn().mockResolvedValue(undefined) }
+ const step = prefetchHogFunctionsStep<TestInput>(hogTransformer, true)
+
+ const results = await step([createInput(3), createInput(4)])
+
+ expect(results.map((result) => result.type)).toEqual(Array(2).fill(PipelineResultType.OK))
+ expect(hogTransformer.prefetchHogFunctionsForTeams).toHaveBeenCalledWith([3, 4])
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep.ts
new file mode 100644
index 000000000000..c57a1d1cd7eb
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchHogFunctionsStep.ts
@@ -0,0 +1,18 @@
+import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
+import { createPrefetchStep } from '~/ingestion/pipelines/analytics/steps/createPrefetchStep'
+import { Team } from '~/types'
+
+type PrefetchHogFunctionsStepInput = { team: Pick<Team, 'id'> }
+
+/** Warms the transformation hog-function cache for the chunk's teams ahead of the hog transformer's per-event lookups. */
+export function prefetchHogFunctionsStep<T extends PrefetchHogFunctionsStepInput>(
+ hogTransformer: Pick<HogTransformer, 'prefetchHogFunctionsForTeams'>,
+ enabled: boolean
+) {
+ return createPrefetchStep<T, number>({
+ name: 'prefetchHogFunctionsStep',
+ extractKey: (event) => event.team.id,
+ load: (teamIds) => hogTransformer.prefetchHogFunctionsForTeams(teamIds),
+ enabled,
+ })
+}
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchTeamsStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchTeamsStep.test.ts
new file mode 100644
index 000000000000..b88923de3b2c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchTeamsStep.test.ts
@@ -0,0 +1,20 @@
+import { PipelineResultType } from '~/ingestion/framework/results'
+import { prefetchTeamsStep } from '~/ingestion/pipelines/analytics/steps/prefetchTeamsStep'
+
+type TestInput = { headers: { token?: string } }
+
+function createInput(token?: string): TestInput {
+ return { headers: { token } }
+}
+
+describe('prefetchTeamsStep', () => {
+ it('warms the team cache by header token, skipping events without one', async () => {
+ const teamManager = { getTeamsByTokens: jest.fn().mockResolvedValue({}) }
+ const step = prefetchTeamsStep<TestInput>(teamManager, true)
+
+ const results = await step([createInput('token-a'), createInput('token-b'), createInput()])
+
+ expect(results.map((result) => result.type)).toEqual(Array(3).fill(PipelineResultType.OK))
+ expect(teamManager.getTeamsByTokens).toHaveBeenCalledWith(['token-a', 'token-b'], { flush: true })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchTeamsStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchTeamsStep.ts
new file mode 100644
index 000000000000..5b3c567c79e7
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchTeamsStep.ts
@@ -0,0 +1,18 @@
+import { TeamManager } from '~/common/utils/team-manager'
+import { createPrefetchStep } from '~/ingestion/pipelines/analytics/steps/createPrefetchStep'
+import { EventHeaders } from '~/types'
+
+type PrefetchTeamsStepInput = { headers: Pick<EventHeaders, 'token'> }
+
+/** Warms the team cache for the chunk's tokens ahead of resolveTeamStep's per-event lookups. */
+export function prefetchTeamsStep<T extends PrefetchTeamsStepInput>(
+ teamManager: Pick<TeamManager, 'getTeamsByTokens'>,
+ enabled: boolean
+) {
+ return createPrefetchStep<T, string>({
+ name: 'prefetchTeamsStep',
+ extractKey: (event) => event.headers.token || null,
+ load: (tokens) => teamManager.getTeamsByTokens(tokens, { flush: true }),
+ enabled,
+ })
+}
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 3411be1184fe..dbf4c4bb981b 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -402,6 +402,9 @@ export class IngestionApiServer implements NodeServer {
preservePartitionLocality: this.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
groupsPrefetchEnabled: this.config.GROUPS_PREFETCH_ENABLED,
+ teamsPrefetchEnabled: this.config.TEAMS_PREFETCH_ENABLED,
+ eventSchemasPrefetchEnabled: this.config.EVENT_SCHEMAS_PREFETCH_ENABLED,
+ hogFunctionsPrefetchEnabled: this.config.HOG_FUNCTIONS_PREFETCH_ENABLED,
outputs: ingestionOutputs,
perDistinctIdOptions: {
SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP: this.config.SKIP_UPDATE_EVENT_AND_PROPERTIES_STEP,
diff --git a/nodejs/tests/ingestion/ingestion-e2e.test.ts b/nodejs/tests/ingestion/ingestion-e2e.test.ts
index 1b04bb444b2e..fb7a3c7930b7 100644
--- a/nodejs/tests/ingestion/ingestion-e2e.test.ts
+++ b/nodejs/tests/ingestion/ingestion-e2e.test.ts
@@ -47,6 +47,9 @@ describe.each([
GROUPS_PREFETCH_ENABLED: false,
GROUP_BATCH_WRITING_USE_BATCH_CREATES: false,
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: false,
+ TEAMS_PREFETCH_ENABLED: false,
+ EVENT_SCHEMAS_PREFETCH_ENABLED: false,
+ HOG_FUNCTIONS_PREFETCH_ENABLED: false,
},
{
PERSONS_PREFETCH_ENABLED: true,
@@ -55,6 +58,9 @@ describe.each([
GROUPS_PREFETCH_ENABLED: true,
GROUP_BATCH_WRITING_USE_BATCH_CREATES: true,
GROUP_BATCH_WRITING_USE_BATCH_UPDATES: true,
+ TEAMS_PREFETCH_ENABLED: true,
+ EVENT_SCHEMAS_PREFETCH_ENABLED: true,
+ HOG_FUNCTIONS_PREFETCH_ENABLED: true,
},
])('Event Pipeline E2E tests (fold+groupBatchCreates=$PERSON_MERGE_FOLD_ENABLED)', (pipelineConfig) => {
const testWithTeamIngester = createTestWithTeamIngester(pipelineConfig, (infra, kafkaProducer) => {