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.

perf(ai-research): free image fetch domain slots before the kafka publish (#106331)

Robbie12baa015da21
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index 6b3b76056efc..48fa1dea7b43 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -36,11 +36,11 @@ A registrable domain remains in memory while it is active, blocked, or has a pen
The fetch pass deduplicates jobs by global canonical ref. It groups the remaining jobs by registrable domain and origin. Two indexed priority queues select work in logarithmic time. Each queue gets a capped proportional concurrency target. The scheduler selects the queue that is furthest below its target. It uses the waiting job count and insertion order as tie-breakers.
-The queue tracks the remaining request slots from active and waiting jobs. It applies the configured registrable-domain and pod limits. When fewer than 48 slots remain, low-diversity mode can start. More than 50 waiting URL jobs must still be eligible for a diversity deferral. The pass processes 8 more jobs. It then republishes each eligible tail job to the frontier. The mode stays active for the rest of the pass. A durable optional marker limits this fast deferral to once per job. Previously deferred jobs proceed normally until the pass deadline.
+The queue tracks the remaining request slots from active and waiting jobs. It applies the configured registrable-domain and pod limits. A job releases its registrable-domain slot when the image response is complete. It keeps its pod slot until Kafka acknowledges the image publish. The worker then starts the next job while the publish continues. When fewer than 48 slots remain, low-diversity mode can start. More than 50 waiting URL jobs must still be eligible for a diversity deferral. The pass processes 8 more jobs. It then republishes each eligible tail job to the frontier. The mode stays active for the rest of the pass. A durable optional marker limits this fast deferral to once per job. Previously deferred jobs proceed normally until the pass deadline.
The frontier consumer uses cooperative rebalancing. Its revoke path drains active work before it releases assigned partitions.
-Each image-fetch worker creates two Kafka group members by default. A local joiner combines their batches before it starts a fetch pass. Group assignments do not overlap, and each member can own multiple partitions. The joiner processes available batches when its join window ends. Each member waits for its group to start before it reads another batch, so a group has at most one contribution per member. The member then tracks completion through the shared Kafka consumer background-task mechanism. Each member can hold two unfinished batches. The consumer waits for the oldest batch at that limit and stores offsets in batch order. Shared request limits still bound total network concurrency. The background-task timeout is 240 seconds, leaving 60 seconds below the default Kafka poll allowance for joining and scheduling. Shutdown stops all consumer loops and waits for the actual joined processing promises before disconnecting consumers and destroying shared dependencies. This wait includes work that outlives the Kafka consumer drain or background-task timeout. The worker divides a 100 MiB Kafka prefetch budget across its group members, with a minimum of 25 MiB per member. This preserves the queue sizes for one to four members and allows a default maximum-sized record in each queue. Sixteen members have a combined prefetch budget of 400 MiB. During a mixed-version rollout, pods with more group members can receive more partitions until the rollout finishes. `SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH` accepts targets from one to sixteen for worker-count experiments.
+Each image-fetch worker creates two Kafka group members by default. A local joiner combines their batches before it starts a fetch pass. When `SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES` is false, each member batch starts its own pass immediately, so a slow partition does not hold back the other members. Group assignments do not overlap, and each member can own multiple partitions. The joiner processes available batches when its join window ends. Each member waits for its group to start before it reads another batch, so a group has at most one contribution per member. The member then tracks completion through the shared Kafka consumer background-task mechanism. Each member can hold two unfinished batches. The consumer waits for the oldest batch at that limit and stores offsets in batch order. Shared request limits still bound total network concurrency. The background-task timeout is 240 seconds, leaving 60 seconds below the default Kafka poll allowance for joining and scheduling. Shutdown stops all consumer loops and waits for the actual joined processing promises before disconnecting consumers and destroying shared dependencies. This wait includes work that outlives the Kafka consumer drain or background-task timeout. The worker divides a 100 MiB Kafka prefetch budget across its group members, with a minimum of 25 MiB per member. This preserves the queue sizes for one to four members and allows a default maximum-sized record in each queue. Sixteen members have a combined prefetch budget of 400 MiB. During a mixed-version rollout, pods with more group members can receive more partitions until the rollout finishes. `SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH` accepts targets from one to sixteen for worker-count experiments.
Retry jobs use 1-minute, 10-minute, and 1-hour Kafka topics. The topics use broker append timestamps.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
index 0b50532fbd88..ff9e9c6715e9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.test.ts
@@ -196,6 +196,42 @@ describe('FetchRunner', () => {
])
})
+ it('starts the next request for a registrable domain while an earlier image publish waits', async () => {
+ const harness = build({ bytes: Buffer.from('image'), contentType: 'image/png' }, {}, 'queued', {
+ ...OPTIONS,
+ maxConcurrentPerRegistrableDomain: 1,
+ })
+ let releasePublish: () => void = () => undefined
+ harness.publishImage.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ releasePublish = resolve
+ })
+ )
+ const second = candidate({
+ originalRef: `imageurl:${'b'.repeat(22)}`,
+ currentUrl: 'https://cdn.example.com/b.png',
+ })
+
+ let passFinished = false
+ const run = harness.runner.run([candidate(), second], new Map()).finally(() => {
+ passFinished = true
+ })
+ await jest.advanceTimersByTimeAsync(0)
+
+ expect(harness.fetch.mock.calls.map(([url]) => url)).toEqual([candidate().currentUrl, second.currentUrl])
+ expect(passFinished).toBe(false)
+ releasePublish()
+ const attempts = await run
+ expect(attempts.map((attempt) => [attempt.candidate.originalRef, attempt.outcome, attempt.lost])).toEqual(
+ expect.arrayContaining([
+ [candidate().originalRef, 'ok', false],
+ [second.originalRef, 'ok', false],
+ ])
+ )
+ expect(attempts).toHaveLength(2)
+ })
+
it('allocates sibling-origin workers by queue share', async () => {
const harness = build({}, {}, 'queued', { ...OPTIONS, maxConcurrentPerRegistrableDomain: 2 })
let releaseFirst: (() => void) | undefined
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
index 208eae0e1b5b..57226e32f12e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner.ts
@@ -203,30 +203,50 @@ export class FetchRunner implements FetchPass {
republishBatch: RepublishBatch,
passState: FetchPassState
): Promise<void> {
+ const leaseWork: Promise<void>[] = []
for (;;) {
const lease = queue.take()
if (!lease) {
- return
+ break
}
- try {
- attempts.push(
- await this.processLease(
- lease,
- stored,
- configurationItems,
- configurationPolicy,
- deadlineMs,
- republishBatch,
- passState
- )
- )
- } catch (error) {
- passState.failure ??= { error }
- queue.abort()
- throw error
- } finally {
+ let signalSlotReleased: () => void = () => undefined
+ const slotReleased = new Promise<void>((resolve) => {
+ signalSlotReleased = resolve
+ })
+ const releaseRegistrableDomainSlot = (): void => {
lease.release()
+ signalSlotReleased()
}
+ const work = (async (): Promise<void> => {
+ try {
+ attempts.push(
+ await this.processLease(
+ lease,
+ stored,
+ configurationItems,
+ configurationPolicy,
+ deadlineMs,
+ republishBatch,
+ passState,
+ releaseRegistrableDomainSlot
+ )
+ )
+ } catch (error) {
+ passState.failure ??= { error }
+ queue.abort()
+ throw error
+ } finally {
+ releaseRegistrableDomainSlot()
+ }
+ })()
+ leaseWork.push(work)
+ await Promise.race([slotReleased, work.catch(() => undefined)])
+ }
+ const failedLease = (await Promise.allSettled(leaseWork)).find(
+ (settled): settled is PromiseRejectedResult => settled.status === 'rejected'
+ )
+ if (failedLease) {
+ throw failedLease.reason
}
}
@@ -237,7 +257,8 @@ export class FetchRunner implements FetchPass {
configurationPolicy: ConfigurationPolicyPass,
deadlineMs: number,
republishBatch: RepublishBatch,
- passState: FetchPassState
+ passState: FetchPassState,
+ releaseRegistrableDomainSlot: () => void
): Promise<FetchAttempt> {
const candidate = lease.candidate
if (candidate.remainingHops === 0) {
@@ -274,7 +295,8 @@ export class FetchRunner implements FetchPass {
configurationItems,
configurationPolicy,
deadlineMs,
- republishBatch
+ republishBatch,
+ releaseRegistrableDomainSlot
)
} catch (error) {
passState.failure ??= { error }
@@ -291,7 +313,8 @@ export class FetchRunner implements FetchPass {
configurationItems: Map<string, ConfigurationCacheItem>,
configurationPolicy: ConfigurationPolicyPass,
deadlineMs: number,
- republishBatch: RepublishBatch
+ republishBatch: RepublishBatch,
+ releaseRegistrableDomainSlot: () => void
): Promise<FetchAttempt> {
if (candidate.remainingHops === 0) {
return this.terminal(candidate, HOPS_EXHAUSTED, undefined, [])
@@ -518,6 +541,7 @@ export class FetchRunner implements FetchPass {
)
}
if (result.outcome === 'ok') {
+ releaseRegistrableDomainSlot()
try {
await this.publisher.publishImage(attemptedCandidate, result)
} catch {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
index 577345344daf..a537b6fc881d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetch-batch-joiner.test.ts
@@ -30,7 +30,7 @@ describe('ImageFetchBatchJoiner', () => {
})
afterEach(() => jest.useRealTimers())
- it.each([2, 16])('joins batches from %i consumers before processing', async (consumerCount) => {
+ it.each([1, 2, 16])('joins batches from %i consumers before processing', async (consumerCount) => {
const pass = deferred()
const processBatch = jest.fn(() => pass.promise)
const joiner = new ImageFetchBatchJoiner(consumerCount, processBatch)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 77e1c031f619..c355ede18524 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -98,8 +98,10 @@ export type MlMirrorConfig = {
SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC: string
SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: string
SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: number
- /** Kafka group members per image-fetch worker. Their batches join into one fetch pass. */
+ /** Kafka group members per image-fetch worker. */
SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: number
+ /** While true, the batches of all group members in one worker join into one fetch pass. While false, each batch starts its own pass. */
+ SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES: boolean
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: string
/** Bounds one DynamoDB request so an unavailable store cannot hold the poll loop. */
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: number
@@ -257,6 +259,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',
SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,
SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 2,
+ SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES: true,
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: '',
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TIMEOUT_MS: 5_000,
AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS: 30 * 24 * 60 * 60,
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
index 07c8104441c5..d21a5327d056 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.test.ts
@@ -4,37 +4,52 @@ import { ImageFetchBatchJoiner } from '../ingestion/pipelines/sessionreplay/ml-m
import {
buildImageFetchConsumerConfigs,
buildImageFetchConsumerOverrides,
+ imageFetchBatchesPerPass,
shutdownImageFetchConsumers,
} from './ingestion-session-replay-ml-image-fetch-server'
import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
describe('image fetch consumer wiring', () => {
it.each([
- ['the default', {}, 2, 102_400],
- ['four consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4, 164_096],
- ['eight consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8 }, 8, 328_192],
- ['sixteen consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 16 }, 16, 656_384],
- ])('creates %s number of Kafka group members', (_name, overrides, expectedConsumers, expectedQueueBudget) => {
- const serverConfig = buildMlMirrorServerConfig(overrides)
- const consumerConfigs = buildImageFetchConsumerConfigs(serverConfig)
- const consumerOverrides = buildImageFetchConsumerOverrides(serverConfig, consumerConfigs.length)
+ ['the default', {}, 2, 2, 102_400],
+ ['four consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 4 }, 4, 4, 164_096],
+ ['eight consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8 }, 8, 8, 328_192],
+ [
+ 'eight unjoined consumers',
+ {
+ SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 8,
+ SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES: false,
+ },
+ 8,
+ 1,
+ 328_192,
+ ],
+ ['sixteen consumers', { SESSION_RECORDING_ML_IMAGE_FETCH_TARGET_PARTITIONS_PER_BATCH: 16 }, 16, 16, 656_384],
+ ])(
+ 'creates %s number of Kafka group members',
+ (_name, overrides, expectedConsumers, expectedBatchesPerPass, expectedQueueBudget) => {
+ const serverConfig = buildMlMirrorServerConfig(overrides)
+ const consumerConfigs = buildImageFetchConsumerConfigs(serverConfig)
+ const consumerOverrides = buildImageFetchConsumerOverrides(serverConfig, consumerConfigs.length)
- expect(consumerConfigs).toHaveLength(expectedConsumers)
- expect(consumerConfigs.every((config) => config.maxBackgroundTasks === 2)).toBe(true)
- expect(consumerConfigs.every((config) => config.backgroundTaskTimeoutMs === 240_000)).toBe(true)
- expect(consumerConfigs.map((config) => config.groupId)).toEqual(
- Array(expectedConsumers).fill(serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID)
- )
- expect(Number(consumerOverrides['queued.max.messages.kbytes']) * expectedConsumers).toBeLessThanOrEqual(
- expectedQueueBudget
- )
- expect(Number(consumerOverrides['queued.max.messages.kbytes']) * expectedConsumers).toBeGreaterThanOrEqual(
- expectedQueueBudget - expectedConsumers
- )
- expect(Number(consumerOverrides['queued.max.messages.kbytes']) * 1024).toBeGreaterThanOrEqual(
- serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
- )
- })
+ expect(consumerConfigs).toHaveLength(expectedConsumers)
+ expect(imageFetchBatchesPerPass(serverConfig, consumerConfigs.length)).toBe(expectedBatchesPerPass)
+ expect(consumerConfigs.every((config) => config.maxBackgroundTasks === 2)).toBe(true)
+ expect(consumerConfigs.every((config) => config.backgroundTaskTimeoutMs === 240_000)).toBe(true)
+ expect(consumerConfigs.map((config) => config.groupId)).toEqual(
+ Array(expectedConsumers).fill(serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID)
+ )
+ expect(Number(consumerOverrides['queued.max.messages.kbytes']) * expectedConsumers).toBeLessThanOrEqual(
+ expectedQueueBudget
+ )
+ expect(Number(consumerOverrides['queued.max.messages.kbytes']) * expectedConsumers).toBeGreaterThanOrEqual(
+ expectedQueueBudget - expectedConsumers
+ )
+ expect(Number(consumerOverrides['queued.max.messages.kbytes']) * 1024).toBeGreaterThanOrEqual(
+ serverConfig.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_IMAGE_BYTES * 2 + 64 * 1024
+ )
+ }
+ )
it.each([false, true])('waits for joined work before disconnecting and cleaning up (failure=%s)', async (fails) => {
jest.useFakeTimers()
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
index 4e948f3de586..9a939496b88f 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -167,6 +167,13 @@ export function buildImageFetchConsumerConfigs(
}))
}
+export function imageFetchBatchesPerPass(
+ config: IngestionSessionReplayMlMirrorServerConfig,
+ consumerCount: number
+): number {
+ return config.SESSION_RECORDING_ML_IMAGE_FETCH_JOIN_MEMBER_BATCHES ? consumerCount : 1
+}
+
export function buildImageFetchConsumerOverrides(
config: IngestionSessionReplayMlMirrorServerConfig,
consumerCount: number
@@ -292,8 +299,9 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSe
logger.info('🌐', 'ml_image_fetch_started', { dryRun })
const consumerConfigs = buildImageFetchConsumerConfigs(this.config)
- const batchJoiner = new ImageFetchBatchJoiner(consumerConfigs.length, (messages) =>
- fetchConsumer.handleBatch(messages, Date.now())
+ const batchJoiner = new ImageFetchBatchJoiner(
+ imageFetchBatchesPerPass(this.config, consumerConfigs.length),
+ (messages) => fetchConsumer.handleBatch(messages, Date.now())
)
const consumerOverrides = buildImageFetchConsumerOverrides(this.config, consumerConfigs.length)
const consumers = consumerConfigs.map(