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): add tenant and cache-outcome attributes to tracing spans (#89882)

José Sequeira1418f17af414
diff --git a/nodejs/src/common/tracing/tracing-utils.ts b/nodejs/src/common/tracing/tracing-utils.ts
index 2112ff333274..2d63d4a38287 100644
--- a/nodejs/src/common/tracing/tracing-utils.ts
+++ b/nodejs/src/common/tracing/tracing-utils.ts
@@ -107,6 +107,30 @@ interface FunctionInstrumentationOptions {
measureTime?: boolean
/** Stamped as the `tag` attribute on the span and the summary metric, to tell apart callers sharing a key. */
tag?: string
+ /** Attributes set on the tracing span only. They never reach the Prometheus metrics. */
+ attributes?: Attributes
+}
+
+/**
+ * True when a span started now would be exported. With parent-based sampling the parent decides,
+ * so callers can skip building attributes for the ~99% of spans a low sample rate discards.
+ */
+export function isTracingActive(): boolean {
+ if (defaultConfig.DISABLE_OPENTELEMETRY_TRACING) {
+ return false
+ }
+ return trace.getActiveSpan()?.isRecording() ?? false
+}
+
+/** Set attributes on the active span. No-op when tracing is disabled or the span is not sampled. */
+export function setSpanAttributes(attrs: Attributes): void {
+ if (defaultConfig.DISABLE_OPENTELEMETRY_TRACING) {
+ return
+ }
+ const span = trace.getActiveSpan()
+ if (span?.isRecording()) {
+ span.setAttributes(attrs)
+ }
}
/**
@@ -126,6 +150,7 @@ export async function instrumentFn<T>(
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 attributes = (typeof options === 'string' ? undefined : options.attributes) ?? {}
const t = timeoutGuard(timeoutMessage, getLoggingContext, timeout, sendException, () => {
instrumentedFunctionTimeout.labels({ function: key }).inc()
@@ -137,7 +162,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, tag ? { tag } : {}, func)
+ : await withSpan('instrumented_function', key, tag ? { ...attributes, tag } : attributes, func)
end?.({ success: 'true' })
if (logExecutionTime) {
logTime(startTime, key)
diff --git a/nodejs/src/common/utils/lazy-loader.test.ts b/nodejs/src/common/utils/lazy-loader.test.ts
index 12ca48b8700c..b06b57255ee1 100644
--- a/nodejs/src/common/utils/lazy-loader.test.ts
+++ b/nodejs/src/common/utils/lazy-loader.test.ts
@@ -1,6 +1,13 @@
+import { setSpanAttributes } from '~/common/tracing/tracing-utils'
+
import { LazyLoader } from './lazy-loader'
import { delay } from './utils'
+jest.mock('~/common/tracing/tracing-utils', () => ({
+ ...jest.requireActual('~/common/tracing/tracing-utils'),
+ setSpanAttributes: jest.fn(),
+}))
+
describe('LazyLoader', () => {
jest.setTimeout(1000)
@@ -195,6 +202,29 @@ describe('LazyLoader', () => {
})
})
+ describe('span attributes', () => {
+ it('records whether keys were cached, loaded, or waited on an in-flight load', async () => {
+ loader.mockResolvedValue({ key1: 'value1' })
+
+ const first = lazyLoader.get('key1')
+ const second = lazyLoader.get('key1')
+ await Promise.all([first, second])
+ await lazyLoader.get('key1')
+
+ expect(jest.mocked(setSpanAttributes).mock.calls.map(([attrs]) => attrs['lazyloader.outcome'])).toEqual([
+ 'loaded',
+ 'waited_pending',
+ 'all_cached',
+ ])
+ expect(jest.mocked(setSpanAttributes)).toHaveBeenLastCalledWith({
+ 'lazyloader.name': 'test',
+ 'lazyloader.keys': 1,
+ 'lazyloader.misses': 0,
+ 'lazyloader.outcome': 'all_cached',
+ })
+ })
+ })
+
describe('refresh behavior', () => {
it('refreshes values after refreshAge', async () => {
loader.mockResolvedValueOnce({ key1: 'value1' }).mockResolvedValueOnce({ key1: 'value2' })
diff --git a/nodejs/src/common/utils/lazy-loader.ts b/nodejs/src/common/utils/lazy-loader.ts
index 05a5c06374cf..96a5bcfc803c 100644
--- a/nodejs/src/common/utils/lazy-loader.ts
+++ b/nodejs/src/common/utils/lazy-loader.ts
@@ -1,6 +1,7 @@
+import { Attributes } from '@opentelemetry/api'
import { Counter, Gauge } from 'prom-client'
-import { instrumentFn } from '~/common/tracing/tracing-utils'
+import { instrumentFn, setSpanAttributes } from '~/common/tracing/tracing-utils'
import { defaultConfig } from '../config/config'
import { logger } from './logger'
@@ -104,6 +105,12 @@ export type LoadOptions = {
type LazyLoaderMap<T> = Record<string, T | null | undefined>
+/**
+ * How a `loadViaCache` call was served: every key from the cache, by invoking the loader, or by
+ * waiting on a load another caller already had in flight.
+ */
+export type LazyLoaderSpanOutcome = 'all_cached' | 'loaded' | 'waited_pending'
+
/**
* A cached value together with the deadlines that govern it. These live on one object so that
* writing a value and stamping its deadlines cannot come apart: any code path that sets the
@@ -272,11 +279,17 @@ export class LazyLoader<T> {
if (keysToLoad.size === 0) {
lazyLoaderFullCacheHits.labels({ name: this.options.name, hit: 'hit' }).inc()
+ setSpanAttributes(this.spanAttributes(keys, keysToLoad, 'all_cached'))
return results
}
lazyLoaderFullCacheHits.labels({ name: this.options.name, hit: 'miss' }).inc()
+ // A span that only waits on another caller's in-flight load has no query child of its
+ // own, so record the distinction here or it looks like a slow cache lookup.
+ const allPending = Array.from(keysToLoad).every((key) => this.pendingLoads[key] !== undefined)
+ setSpanAttributes(this.spanAttributes(keys, keysToLoad, allPending ? 'waited_pending' : 'loaded'))
+
// We have something to load so we schedule it and then await all of them
await this.load(Array.from(keysToLoad), options)
@@ -289,6 +302,15 @@ export class LazyLoader<T> {
})
}
+ private spanAttributes(keys: string[], keysToLoad: Set<string>, outcome: LazyLoaderSpanOutcome): Attributes {
+ return {
+ 'lazyloader.name': this.options.name,
+ 'lazyloader.keys': keys.length,
+ 'lazyloader.misses': keysToLoad.size,
+ 'lazyloader.outcome': outcome,
+ }
+ }
+
/**
* Schedules the keys to be loaded with a buffer to allow batching multiple keys
* This is somewhat complex but simplifies the usage around the codebase as you can safely do multiple gets without worrying about firing off duplicate DB requests
diff --git a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
index a39d7bbf6363..695b1d784c24 100644
--- a/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
+++ b/nodejs/src/ingestion/common/persons/batch-writing-person-store.ts
@@ -29,6 +29,7 @@ import {
PersonRepository,
} from '~/common/persons/repositories/person-repository'
import { PersonRepositoryTransaction } from '~/common/persons/repositories/person-repository-transaction'
+import { withTracingSpan } from '~/common/tracing/tracing-utils'
import { CreatePersonResult, MoveDistinctIdsResult } from '~/common/utils/db/db'
import { MessageSizeTooLarge } from '~/common/utils/db/error'
import { logger } from '~/common/utils/logger'
@@ -1109,10 +1110,29 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
} else {
personFetchForCheckingCacheOperationsCounter.inc({ operation: 'hit' })
cache.getCheckCachedPerson(teamId, distinctId)
+ return this.awaitPendingFetch(teamId, distinctId, 'checking', fetchPromise)
}
return fetchPromise
}
+ /**
+ * Waiting on another caller's in-flight fetch has no query span of its own, so without this
+ * the wait is invisible in a trace and reads as time spent inside the step.
+ */
+ private awaitPendingFetch<T>(
+ teamId: Team['id'],
+ distinctId: string,
+ pending: 'checking' | 'update' | 'prefetch',
+ promise: Promise<T>
+ ): Promise<T> {
+ return withTracingSpan(
+ 'persons-store',
+ 'personsStore.awaitPendingFetch',
+ { team_id: teamId, distinct_id: distinctId, 'persons.pending_fetch': pending },
+ () => promise
+ )
+ }
+
/**
* 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
@@ -1247,7 +1267,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
// and then return from cache (prefetch populates both caches)
const prefetchPromise = this.fetchPromisesForChecking.get(cacheKey)
if (prefetchPromise) {
- await prefetchPromise
+ await this.awaitPendingFetch(teamId, distinctId, 'prefetch', prefetchPromise)
const prefetchedPerson = cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)
if (prefetchedPerson !== undefined) {
return prefetchedPerson === null ? null : toInternalPerson(prefetchedPerson)
@@ -1294,6 +1314,7 @@ export class BatchWritingPersonsStore implements PersonsStore, BatchWritingStore
} else {
personFetchForUpdateCacheOperationsCounter.inc({ operation: 'hit' })
cache.getCachedPersonForUpdateByDistinctId(teamId, distinctId)
+ return this.awaitPendingFetch(teamId, distinctId, 'update', fetchPromise)
}
return fetchPromise
}
diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
index 85ef0b470e5b..2219054f50ed 100644
--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
@@ -45,8 +45,14 @@ export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string
if (successfulValues.length > 0) {
const end = pipelineStepDurationHistogram.startTimer({ step_name: stepName, step_type: 'chunk' })
try {
- stepResults = await instrumentFn({ key: stepName, sendException: false, measureTime: false }, () =>
- step(successfulValues)
+ stepResults = await instrumentFn(
+ {
+ key: stepName,
+ sendException: false,
+ measureTime: false,
+ attributes: { chunk_size: successfulValues.length },
+ },
+ () => step(successfulValues)
)
end({ result: 'chunk' })
} catch (e) {
diff --git a/nodejs/src/ingestion/framework/span-attributes.test.ts b/nodejs/src/ingestion/framework/span-attributes.test.ts
new file mode 100644
index 000000000000..57eff922aa72
--- /dev/null
+++ b/nodejs/src/ingestion/framework/span-attributes.test.ts
@@ -0,0 +1,31 @@
+import { eventSpanAttributes } from './span-attributes'
+
+describe('eventSpanAttributes', () => {
+ it.each([
+ ['non-object input', 'nope', {}],
+ ['unknown shape', { foo: 'bar' }, {}],
+ [
+ 'team + raw event',
+ { team: { id: 7 }, event: { event: '$pageview', distinct_id: 'u1' } },
+ { team_id: 7, distinct_id: 'u1', event: '$pageview' },
+ ],
+ [
+ 'teamId + normalizedEvent wins over event',
+ {
+ teamId: 3,
+ event: { event: 'raw', distinct_id: 'r' },
+ normalizedEvent: { event: 'norm', distinct_id: 'n' },
+ },
+ { team_id: 3, distinct_id: 'n', event: 'norm' },
+ ],
+ [
+ 'preparedEvent uses camelCase distinctId',
+ { team: { id: 9 }, preparedEvent: { event: 'e', distinctId: 'p' } },
+ { team_id: 9, distinct_id: 'p', event: 'e' },
+ ],
+ ['team id from the event when no team object', { event: { team_id: 5 } }, { team_id: 5 }],
+ ['ignores fields of the wrong type', { teamId: '5', event: { event: 1, distinct_id: null } }, {}],
+ ])('%s', (_name, input, expected) => {
+ expect(eventSpanAttributes(input)).toEqual(expected)
+ })
+})
diff --git a/nodejs/src/ingestion/framework/span-attributes.ts b/nodejs/src/ingestion/framework/span-attributes.ts
new file mode 100644
index 000000000000..6169ecd552db
--- /dev/null
+++ b/nodejs/src/ingestion/framework/span-attributes.ts
@@ -0,0 +1,52 @@
+import { Attributes } from '@opentelemetry/api'
+
+/**
+ * Attributes that identify the tenant, actor and action of a step span, so slow spans can be
+ * broken down by who caused them. The keys match the dimensions TopHog and the APM span store
+ * already use, so the two can be joined by eye.
+ */
+export interface EventSpanAttributes extends Attributes {
+ team_id?: number
+ distinct_id?: string
+ event?: string
+}
+
+type Loose = Record<string, unknown>
+
+function asRecord(value: unknown): Loose | undefined {
+ return value !== null && typeof value === 'object' ? (value as Loose) : undefined
+}
+
+/**
+ * Derive span attributes from a step input by its well-known fields. Steps get many input shapes
+ * (`team`, `teamId`, `event`, `normalizedEvent`, `preparedEvent`, ...), so this reads whatever is
+ * present rather than making every step declare attributes. Unknown shapes yield `{}`.
+ */
+export function eventSpanAttributes(input: unknown): EventSpanAttributes {
+ const record = asRecord(input)
+ if (!record) {
+ return {}
+ }
+
+ const event = asRecord(record.preparedEvent) ?? asRecord(record.normalizedEvent) ?? asRecord(record.event)
+ const team = asRecord(record.team)
+
+ const attrs: EventSpanAttributes = {}
+
+ const teamId = team?.id ?? record.teamId ?? event?.team_id ?? event?.teamId
+ if (typeof teamId === 'number') {
+ attrs.team_id = teamId
+ }
+
+ const distinctId = event?.distinct_id ?? event?.distinctId
+ if (typeof distinctId === 'string') {
+ attrs.distinct_id = distinctId
+ }
+
+ const eventName = event?.event
+ if (typeof eventName === 'string') {
+ attrs.event = eventName
+ }
+
+ return attrs
+}
diff --git a/nodejs/src/ingestion/framework/step-pipeline.ts b/nodejs/src/ingestion/framework/step-pipeline.ts
index 2d06612fef9a..c3fadb8b4f3e 100644
--- a/nodejs/src/ingestion/framework/step-pipeline.ts
+++ b/nodejs/src/ingestion/framework/step-pipeline.ts
@@ -1,9 +1,10 @@
-import { instrumentFn } from '~/common/tracing/tracing-utils'
+import { instrumentFn, isTracingActive } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
import { pipelineStepDurationHistogram } from './metrics'
import { OkResultWithContext, Pipeline, PipelineResultWithContext } from './pipeline.interface'
import { PipelineResult, PipelineResultType, isOkResult } from './results'
+import { eventSpanAttributes } from './span-attributes'
import { ProcessingStep } from './steps'
export class StepPipeline<TInput, TIntermediate, TOutput, C, RPrev extends string = never, RStep extends string = never>
@@ -40,8 +41,14 @@ export class StepPipeline<TInput, TIntermediate, TOutput, C, RPrev extends strin
const end = pipelineStepDurationHistogram.startTimer({ step_name: this.stepName, step_type: 'element' })
let currentResult: PipelineResult<TOutput, RStep>
try {
- currentResult = await instrumentFn({ key: this.stepName, sendException: false, measureTime: false }, () =>
- this.currentStep(previousResult.value)
+ currentResult = await instrumentFn(
+ {
+ key: this.stepName,
+ sendException: false,
+ measureTime: false,
+ attributes: isTracingActive() ? eventSpanAttributes(previousResult.value) : undefined,
+ },
+ () => this.currentStep(previousResult.value)
)
end({ result: PipelineResultType[currentResult.type].toLowerCase() })
} catch (e) {