: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
feat(usage): collect the remaining nodejs usage records (#89874)
Ben White16681d959f03
diff --git a/docs/internal/usage-record-producers.md b/docs/internal/usage-record-producers.mdindex f113d665a3e3..443c2fb0e4ad 100644--- a/docs/internal/usage-record-producers.md+++ b/docs/internal/usage-record-producers.md@@ -12,6 +12,8 @@ So a producer's `record_id` has to be a stable identity for the billed thing: thWhat it protects against is our own duplication, not a sender's.If someone sends the same thing twice we ingest it twice and bill it twice, which is correct.The identity exists so our retries and reprocessing of one ingested thing collapse to one row.+`usage_key` is in the key, so a `record_id` does not repeat it.+CDP is the one producer that still prefixes, because its three call sites share one `usage_key` and the prefix is what separates them.`timestamp` is in the sort key as a date, because every billing read filters a time range and a date in the key prunes where a skip index only skips granules.Every producer stamps it from its own clock when it flushes, never from anything a customer sends — a customer-controlled value would decide whether their own records deduplicate.@@ -24,13 +26,23 @@ Read with `argMax(quantity, timestamp)` grouped by the sort key. HogQL rejects `The collapse happens on merge, so a plain `sum(quantity)` counts every un-merged duplicate.Measured locally: two identical batches landing in separate parts read as 6 rows summing 18 without `FINAL`, and 3 rows summing 9 with it.-| producer_id | usage_key | unit | record_id | deployment |-| ---------------- | -------------------------- | ----------- | ----------------------------------------------------------------------------------------------- | --------------------- |-| `ingestion` | `events`, `ai_events` | events | `{day}:{event}:{distinct_id}:{uuid}` | ingestion consumers |-| `ai-ingestion` | `ai_events` | events | `{day}:{event}:{distinct_id}:{uuid}` | AI ingestion consumer |-| `error-tracking` | `exceptions` | events | `{day}:{event}:{distinct_id}:{uuid}` | error tracking server |-| `cdp` | `cdp_billable_invocations` | invocations | `event:{eventUuid}` / `flow:{invocationId}:{actionStepCount}:{kind}` / `webhook:{invocationId}` | CDP consumers |-| `feature-flags` | `feature_flag_requests` | requests | fresh UUIDv7 per flush | feature flags service |+| producer_id | usage_key | unit | record_id | deployment |+| ------------------- | ----------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------- |+| `ingestion` | `events`, `ai_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |+| `ai-ingestion` | `ai_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | AI ingestion consumer |+| `error-tracking` | `exceptions` | events | `{day}:{sha256 of event, distinct_id, uuid}` | error tracking server |+| `cdp` | `cdp_billable_invocations` | invocations | `event:{eventUuid}` / `flow:{invocationId}:{actionStepCount}:{kind}` / `webhook:{invocationId}` | CDP consumers |+| `feature-flags` | `feature_flag_requests`, `feature_flag_local_evaluation_requests` | requests | fresh UUIDv7 per flush | feature flags service |+| `ingestion` | `survey_responses` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |+| `warehouse-sources` | `warehouse_rows_synced` | rows | the ExternalDataJob ID | warehouse sources worker |+| `batch-exports` | `batch_export_rows` | rows | the BatchExportRun ID | batch exports worker |+| `replay-vision` | `replay_vision_credits` | credits | the observation ID | replay vision worker |+| `logs` | `logs_bytes`, `logs_records` | bytes, records | fresh UUIDv7 per flush | logs ingestion server |+| `apm-traces` | `apm_traces_bytes`, `apm_traces_spans` | bytes, records | fresh UUIDv7 per flush | traces ingestion server |+| `session-replay` | `session_replay_recordings`, `mobile_replay_recordings` | recordings | the session ID | session replay consumer |+| `ingestion` | `enhanced_person_events` | events | `{day}:{sha256 of event, distinct_id, uuid}` | ingestion consumers, ingestion API |++APM names its producer and meters for the signal they carry, not for the product, so metrics get their own names alongside traces rather than inheriting a bare `apm_` prefix that already means spans.Every producer reads the same four env vars, and each one is its own deployment, so one name still rolls out per producer from that service's own config.@@ -47,6 +59,12 @@ There is deliberately no percentage option: sampling a share of a team's eventsEvery record carries quantity 1 and names one billed thing, so the aggregate lives in ClickHouse rather than in the producer.A producer that sees the same identity twice sends one record, because two records sharing an identity collapse rather than add.+Three producers break that shape: feature flags, logs and APM send per-flush aggregates rather than one record per billed thing.+They have no identity to reproduce, so each flush mints a fresh UUIDv7.+That makes them retry-safe but not replay-safe, and it is deliberate: the quantity is a delta over a window, so a replayed flush is new usage rather than the same usage seen twice.+Deriving those IDs from a clock instead would let two pods flushing one team in the same millisecond collapse into one row and drop a real quantity.+Note the existing nightly report reaches the same totals additively — `app_metrics2` is an `AggregatingMergeTree` summing `count` per hour — so it has no identity to collide in the first place.+## Analytics ingestion```mermaid@@ -89,7 +107,7 @@ The AI check matches the exact names in `AI_EVENT_TYPES` rather than the `$ai_`Overflow is not a drop. A redirected event is consumed again on the overflow lane, whose consumer reports under its own topic and partition, so it is counted exactly once.-### Why the identity mirrors the events table+### Why the identity is `{day}:{sha256 of event, distinct_id, uuid}`The first version of this keyed a record on the batch's consumed offset range and carried the batch's count.That is not replay-safe: Kafka does not promise the same batch boundaries twice, so a replay produces different IDs and the totals add.@@ -101,6 +119,7 @@ Measured after the change: the same events re-consumed by a fresh consumer groupThe UUID alone is not that identity. `sharded_events` is itself a `ReplacingMergeTree` sorted by `(team_id, toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid))`, so two events sharing a UUID but differing in day, name or distinct ID are separate rows there.The nightly report counts them separately too — `get_teams_with_billable_event_count_in_period` counts `distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)` — so keying on the UUID alone would have collapsed rows the report bills for.The `record_id` therefore carries that whole tuple minus the team the billing sorting key already holds. The timestamp is UTC-normalized upstream, so its first ten characters are the day `toDate` resolves.+The tuple is hashed rather than joined, because event names and distinct IDs are client-supplied and together exceed the 512-byte identifier the service accepts. One oversized record makes the service reject the whole request, dropping every record batched with it.The cost is one record per event rather than one per batch. Records are still batched into requests of up to `USAGE_INGESTION_MAX_BATCH_SIZE`, so the request count is a function of batch size, not event count.@@ -159,6 +178,10 @@ Three call sites report, each next to the app metric it is independent of:The event-triggered site bills once per triggering event, not per destination, matching the existing app metric.The workflow site keys on `actionStepCount` so a cyclotron retry of the same step reuses the ID and deduplicates, while a loop that revisits the same action gets a new one and bills again.+The webhook site mints its `invocationId` when it receives the request, which is what we want: ten webhooks carrying one sender-side ID are ten things we ingested and ten things we bill.+The ID only has to survive our own retry of that one receipt, which it does.+The three CDP sites share one `usage_key`, which is why they are the only producer that still prefixes its `record_id`.+The reporter flushes on a timer rather than at a consumer batch boundary, and `CdpBaseConsumer.stop()` flushes it, so a graceful deploy loses nothing.An ungraceful exit can still lose up to one interval of records per pod.@@ -174,6 +197,10 @@ ID reuse is therefore scoped to the retry the gRPC client performs on one requesSends go through a bounded queue drained by one owned task, and `shutdown` closes the queue and awaits it within the aggregator's flush timeout, so a deploy does not lose records Redis just credited.A full queue drops and counts the drop rather than growing; Redis still holds the authoritative count.+The two billable request types get their own usage keys, because the report prices them apart: `billable_feature_flag_requests_count_in_period` is `decide + local_evaluation * 10`.+The producer reports what happened and leaves the weighting downstream, so a decide request lands under `feature_flag_requests` and a local evaluation under `feature_flag_local_evaluation_requests`, both at their raw counts.+Remote config requests are telemetry and bill on neither side.+## Trying it locallyThe service's compose entry sits behind the `ingestion` profile and builds from source, so run it from cargo instead:@@ -201,4 +228,21 @@ FROM billing_usage_records GROUP BY 1, 2 ORDER BY 1, 2## What is not reported yet-Session replay, surveys, data warehouse rows synced, batch export rows, logs and APM all still reach billing only through the nightly usage report.+All current collectors mirror usage into usage-ingestion. Existing billing still reads the nightly usage report.++## Where a collector still disagrees with the report++Each row is a case where the two systems would bill the same team differently, so they have to be closed before billing reads these records.++| usage_key | the report counts | the collector counts | effect |+| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------- |+| `survey_responses` | one response per `$survey_submission_id` per survey, and nothing for a survey attached to a product tour | every `survey sent` event | over-bills repeat submissions and product tours |+| `warehouse_rows_synced` | nothing for a source created within seven days of the period end, and nothing at all during the warehouse free period | every completed billable job | over-bills a source's first week |+| `feature_flag_local_evaluation_requests` | every local evaluation request | only the ones the Rust service answers | Django's own endpoint writes no record |++The flags row is about routing, not counting.+The Rust service records both billable request types - `Decide` from the decide handler, `FlagDefinitions` from the local-evaluation handler - and each has its own usage key.+Django still serves `/api/feature_flag/local_evaluation` too, and that path increments the report's counter without writing a usage record, so whatever Contour routes there is uncollected.++Session replay is the closest of the ones that were closed: the collector bills a new session under `session_replay_recordings` only when it is not mobile, and under `mobile_replay_recordings` only for the four SDKs the report bills.+It still bills a recording the report would later drop for `is_deleted`, because deletion happens after the session is counted.diff --git a/nodejs/src/common/usage-ingestion/index.test.ts b/nodejs/src/common/usage-ingestion/index.test.tsnew file mode 100644index 000000000000..89622aedea6b--- /dev/null+++ b/nodejs/src/common/usage-ingestion/index.test.ts@@ -0,0 +1,23 @@+import { createEventUsageBatchFactory } from './index'++describe('createEventUsageBatchFactory', () => {+ const config = {+ USAGE_INGESTION_ADDR: 'localhost:7143',+ USAGE_INGESTION_TLS: false,+ USAGE_INGESTION_TIMEOUT_MS: 5_000,+ USAGE_INGESTION_MAX_BATCH_SIZE: 500,+ USAGE_INGESTION_REPORT_TEAMS: '2,4',+ }++ // A batch that accepts nothing reports nothing, and that silence reads the same as a+ // working collector with no traffic. Both halves of the config have to reach the batch,+ // or a deployment looks enabled and bills nobody.+ it.each([+ ['bills a listed team when the address and the team list are both set', config, true],+ ['bills nothing when the address is empty', { ...config, USAGE_INGESTION_ADDR: '' }, false],+ ['bills nothing when the team list is empty', { ...config, USAGE_INGESTION_REPORT_TEAMS: '' }, false],+ ['bills nothing for a team outside the list', { ...config, USAGE_INGESTION_REPORT_TEAMS: '4' }, false],+ ])('%s', (_name, usageConfig, billed) => {+ expect(createEventUsageBatchFactory(usageConfig, 'events')().accepts(2)).toBe(billed)+ })+})diff --git a/nodejs/src/common/usage-ingestion/index.ts b/nodejs/src/common/usage-ingestion/index.tsindex 67d3134e6c68..204fb02f95e7 100644--- a/nodejs/src/common/usage-ingestion/index.ts+++ b/nodejs/src/common/usage-ingestion/index.ts@@ -3,6 +3,7 @@ import { buildIntegerMatcher } from '~/common/config/config'import { ValueMatcher } from '~/types'import { UsageIngestionClient } from './client'+import { UsageRecordBatch } from './usage-record-batch'export type UsageIngestionConfig = Pick<CommonConfig,@@ -13,13 +14,27 @@ export type UsageIngestionConfig = Pick<| 'USAGE_INGESTION_REPORT_TEAMS'>-export type UsageReportSite = 'events' | 'ai_events' | 'exceptions' | 'cdp'+export type UsageReportSite =+ | 'events'+ | 'ai_events'+ | 'exceptions'+ | 'cdp'+ | 'surveys'+ | 'logs'+ | 'apm_traces'+ | 'session_replay'+ | 'enhanced_persons'const PRODUCER_IDS = {events: 'ingestion',ai_events: 'ai-ingestion',exceptions: 'error-tracking',cdp: 'cdp',+ surveys: 'ingestion',+ logs: 'logs',+ apm_traces: 'apm-traces',+ session_replay: 'session-replay',+ enhanced_persons: 'ingestion',} as constexport function usageReportTeamMatcher(config: UsageIngestionConfig): ValueMatcher<number> {@@ -41,3 +56,21 @@ export function createUsageIngestionClient(maxBatchSize: config.USAGE_INGESTION_MAX_BATCH_SIZE,})}++/**+ * The batch every event pipeline bills through, one per batch and one client per process,+ * because each client owns a transport. Shared so a new pipeline host cannot half-wire it:+ * a client built without an address reports nothing, and that silence is indistinguishable+ * from a working collector with no traffic.+ *+ * `events` is the unit the meters an event pipeline bills share; a record for a meter+ * counted in something else passes its own unit to {@link UsageRecordBatch.add}.+ */+export function createEventUsageBatchFactory(+ config: UsageIngestionConfig,+ site: UsageReportSite+): () => UsageRecordBatch {+ const client = createUsageIngestionClient(config, site)+ const isTeamEnabled = usageReportTeamMatcher(config)+ return () => new UsageRecordBatch(client, { unit: 'events', isTeamEnabled })+}diff --git a/nodejs/src/common/usage-ingestion/usage-record-batch.test.ts b/nodejs/src/common/usage-ingestion/usage-record-batch.test.tsindex c5ee5313aee8..ba66d4be88af 100644--- a/nodejs/src/common/usage-ingestion/usage-record-batch.test.ts+++ b/nodejs/src/common/usage-ingestion/usage-record-batch.test.ts@@ -55,6 +55,18 @@ describe('UsageRecordBatch', () => {expect(ingested[0].map((r) => r.teamId)).toEqual([2])})+ it('keeps an aggregate record its own quantity and unit', async () => {+ const b = new UsageRecordBatch(client, { unit: 'bytes', isTeamEnabled: () => true })+ b.add(1, 'logs_bytes', 'logs:1', 42, 'bytes')+ b.add(1, 'logs_records', 'logs:2', 3, 'records')+ await b.flush()++ expect(ingested[0]).toEqual([+ expect.objectContaining({ usageKey: 'logs_bytes', quantity: 42, unit: 'bytes' }),+ expect.objectContaining({ usageKey: 'logs_records', quantity: 3, unit: 'records' }),+ ])+ })+it('does not send twice for one accumulation', async () => {const b = batch()b.add(1, 'events', 'uuid-1')diff --git a/nodejs/src/common/usage-ingestion/usage-record-batch.ts b/nodejs/src/common/usage-ingestion/usage-record-batch.tsindex bb8ecb6cea34..01acdf1e7627 100644--- a/nodejs/src/common/usage-ingestion/usage-record-batch.ts+++ b/nodejs/src/common/usage-ingestion/usage-record-batch.ts@@ -11,6 +11,8 @@ interface PendingRecord {teamId: numberusageKey: stringrecordId: string+ quantity: number+ unit?: string}/**@@ -36,18 +38,18 @@ export class UsageRecordBatch {return this.records.size}- /** Whether a record for this team would be kept, so a caller can skip building one. */+ /** Whether this team's records would be kept, so a caller can skip building one. */accepts(teamId: number): boolean {return this.client !== null && this.config.isTeamEnabled(teamId)}- add(teamId: number, usageKey: string, recordId: string): void {- if (!this.accepts(teamId)) {+ add(teamId: number, usageKey: string, recordId: string, quantity = 1, unit?: string): void {+ if (quantity <= 0 || !this.accepts(teamId)) {return}const key = `${teamId}:${usageKey}:${recordId}`if (!this.records.has(key)) {- this.records.set(key, { teamId, usageKey, recordId })+ this.records.set(key, { teamId, usageKey, recordId, quantity, unit })}}@@ -62,7 +64,7 @@ export class UsageRecordBatch {usageKey: string,recordId: string): void {- // A team that is not reporting must not put the flush behind its Kafka writes.+ // A record that would be dropped must not put the flush behind its Kafka writes.if (!this.accepts(teamId)) {return}@@ -100,8 +102,8 @@ export class UsageRecordBatch {recordId: record.recordId,teamId: record.teamId,usageKey: record.usageKey,- unit: this.config.unit,- quantity: 1,+ unit: record.unit ?? this.config.unit,+ quantity: record.quantity,timestampMs,}))this.records.clear()diff --git a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.tsindex 03f1164fc84b..927c80555c52 100644--- a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts@@ -40,7 +40,7 @@ export interface CreateEventStepInput {historicalMigration: booleanheaders: EventHeadersmessage: Message- eventUsageRecord?: EventUsageRecord+ eventUsageRecords?: EventUsageRecord[]eventUsageBatch?: UsageRecordBatch}@@ -49,7 +49,7 @@ export interface CreateEventStepResult<O extends string> {teamId: numberheaders: EventHeadersmessage: Message- eventUsageRecord?: EventUsageRecord+ eventUsageRecords?: EventUsageRecord[]eventUsageBatch?: UsageRecordBatch}@@ -67,7 +67,7 @@ export function createCreateEventStep<O extends string, T extends CreateEventStehistoricalMigration,headers,message,- eventUsageRecord,+ eventUsageRecords,eventUsageBatch,} = input@@ -99,7 +99,7 @@ export function createCreateEventStep<O extends string, T extends CreateEventSteteamId: preparedEvent.teamId,headers,message,- eventUsageRecord,+ eventUsageRecords,eventUsageBatch,}diff --git a/nodejs/src/ingestion/common/steps/event-processing/create-event.ts b/nodejs/src/ingestion/common/steps/event-processing/create-event.tsindex 9bda07434534..6bbdf5e9e869 100644--- a/nodejs/src/ingestion/common/steps/event-processing/create-event.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/create-event.ts@@ -41,6 +41,14 @@ export function getElementsChain(properties: Properties): string {return elementsChain}+/** A force upgrade only happens when the client asked for propertyless, and it overrides that ask. */+export function resolvePersonMode(person: Person | undefined, processPerson: boolean): PersonMode {+ if (person?.force_upgrade) {+ return 'force_upgrade'+ }+ return processPerson ? 'full' : 'propertyless'+}+export function createEvent(preIngestionEvent: PreIngestionEvent,person: Person | undefined,@@ -80,13 +88,6 @@ export function createEvent(}}- let personMode: PersonMode = 'full'- if (person?.force_upgrade) {- personMode = 'force_upgrade'- } else if (!processPerson) {- personMode = 'propertyless'- }-// Use person UUID if available, otherwise generate deterministic UUID from distinct_idconst personId = person?.uuid ?? uuidFromDistinctId(teamId, distinctId)@@ -104,7 +105,7 @@ export function createEvent(person_id: personId,person_properties: eventPersonProperties,person_created_at: person?.created_at ?? null,- person_mode: personMode,+ person_mode: resolvePersonMode(person, processPerson),// Only include historical_migration when true to avoid bloating messages...(historicalMigration ? { historical_migration: true } : {}),}diff --git a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.tsindex 816a4e61375d..154439ea984b 100644--- a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts@@ -28,7 +28,7 @@ export interface EmitEventStepInput<O extends string> {teamId: numberheaders: EventHeadersmessage: Message- eventUsageRecord?: EventUsageRecord+ eventUsageRecords?: EventUsageRecord[]eventUsageBatch?: UsageRecordBatch}@@ -54,7 +54,7 @@ export interface EmitEventStepOutput {* been ingested. Empty when nothing was emitted.*/ingested: Promise<IngestedEventInfo | null>[]- eventUsageRecord?: EventUsageRecord+ eventUsageRecords?: EventUsageRecord[]eventUsageBatch?: UsageRecordBatch}@@ -119,7 +119,7 @@ export function createEmitEventStep<O extends string, T extends EmitEventStepInpok({ingested,- eventUsageRecord: input.eventUsageRecord,+ eventUsageRecords: input.eventUsageRecords,eventUsageBatch: input.eventUsageBatch,},ingesteddiff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.test.tsindex b2bdc281051f..10e843c5d2f6 100644--- a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts@@ -1,10 +1,21 @@+import { DateTime } from 'luxon'+import { UsageIngestionClient, UsageRecordInput } from '~/common/usage-ingestion/client'import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'import { isOkResult } from '~/ingestion/framework/results'+import { Person } from '~/types'import { createRecordEventUsageAfterIngestStep, createRecordEventUsageStep } from './usage-records-steps'+const forceUpgradedPerson = (): Person => ({+ team_id: 42,+ properties: {},+ uuid: 'person-uuid',+ created_at: DateTime.fromISO('2026-06-01T00:00:00.000Z'),+ force_upgrade: true,+})+describe('usage-records-steps', () => {const FLUSH_TIMESTAMP_MS = 1_700_000_000_000@@ -30,7 +41,8 @@ describe('usage-records-steps', () => {async function queueEventUsage(ingested: Promise<IngestedEventInfo | null>[],- event: Partial<{ event: string; eventUuid: string; distinctId: string }> = {}+ event: Partial<{ event: string; eventUuid: string; distinctId: string }> = {},+ personProcessing: { processPerson?: boolean; person?: Person } = {}): Promise<void> {const prepare = createRecordEventUsageStep(() => 'events')const prepared = await prepare({@@ -43,6 +55,7 @@ describe('usage-records-steps', () => {...event,},eventUsageBatch,+ ...personProcessing,})expect(isOkResult(prepared)).toBe(true)if (!isOkResult(prepared)) {@@ -127,8 +140,29 @@ describe('usage-records-steps', () => {unit: 'events',quantity: 1,timestampMs: FLUSH_TIMESTAMP_MS,- dimensions: undefined,},])})++ // The meters have to match `person_mode` in the nightly report's two billable-event queries,+ // which count `full` and `force_upgrade` as enhanced and `propertyless` as not. A force upgrade+ // only happens when the client asked for propertyless, so it is the case that breaks if the+ // step goes back to reading `processPerson` alone.+ it.each([+ ['full', { processPerson: true }, ['events', 'enhanced_person_events']],+ ['propertyless', { processPerson: false }, ['events']],+ [+ 'force_upgrade',+ { processPerson: false, person: forceUpgradedPerson() },+ ['events', 'enhanced_person_events'],+ ],+ ])('bills %s person processing under %j', async (_mode, personProcessing, expectedUsageKeys) => {+ await queueEventUsage([Promise.resolve({ topic: 'events', partition: 0 })], {}, personProcessing)++ await eventUsageBatch.flush()++ expect(ingestedUsage.map((record) => record.usageKey)).toEqual(expectedUsageKeys)+ // One event, so both meters share the identity and are told apart only by the usage key.+ expect(new Set(ingestedUsage.map((record) => record.recordId)).size).toBe(1)+ })})diff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.tsindex 5f9923cfdd3c..99ba4da57ffa 100644--- a/nodejs/src/ingestion/common/steps/usage-records-steps.ts+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.ts@@ -1,11 +1,13 @@import { createHash } from 'node:crypto'import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { resolvePersonMode } from '~/ingestion/common/steps/event-processing/create-event'import { IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'-import { UsageKeyResolver } from '~/ingestion/common/usage-records/billable-events'+import { EVENTS_USAGE_KEY, UsageKeyResolver } from '~/ingestion/common/usage-records/billable-events'import { BeforeBatchStep } from '~/ingestion/framework/batching-pipeline'import { PipelineResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'+import { Person } from '~/types'export interface EventUsageBatchContext {eventUsageBatch: UsageRecordBatch@@ -27,6 +29,8 @@ export function createEventUsageBeforeBatchStep<TInput, CInput, CBatch>(export interface RecordEventUsageInput {preparedEvent: { teamId: number; event: string; eventUuid: string; distinctId: string; timestamp: string }eventUsageBatch: UsageRecordBatch+ processPerson?: boolean+ person?: Person}/**@@ -57,13 +61,18 @@ export interface EventUsageRecord {}export interface EventUsageRecordContext {- eventUsageRecord?: EventUsageRecord+ eventUsageRecords?: EventUsageRecord[]}/*** One record per event. Its identity travels inside the event, so a replay reproduces it* whatever the consumer's batching, which an offset-derived identity cannot.*+ * Person processing bills a second record under its own usage key, matching the nightly report,+ * which counts the same event under both meters. It shares the identity, which the usage key+ * separates, and it waits on the same acknowledgement: an event that never lands should not bill+ * for the person work either.+ ** TODO: decide how usage records should treat events dated in the past. This step bills every* billable event at the moment it is processed, including a historical migration. The nightly* report does not: `get_teams_with_billable_event_count_in_period` filters the events table on@@ -78,13 +87,26 @@ export function createRecordEventUsageStep<T extends RecordEventUsageInput>(resolveUsageKey: UsageKeyResolver): ProcessingStep<T, T & EventUsageRecordContext> {return function recordEventUsageStep(input: T): Promise<PipelineResult<T & EventUsageRecordContext>> {- const usageKey = input.eventUsageBatch.accepts(input.preparedEvent.teamId)- ? resolveUsageKey(input.preparedEvent.event)- : undefined- const eventUsageRecord = usageKey- ? { teamId: input.preparedEvent.teamId, usageKey, recordId: analyticsRecordId(input.preparedEvent) }- : undefined- return Promise.resolve(ok({ ...input, eventUsageRecord }))+ if (!input.eventUsageBatch.accepts(input.preparedEvent.teamId)) {+ return Promise.resolve(ok({ ...input, eventUsageRecords: undefined }))+ }+ const usageKey = resolveUsageKey(input.preparedEvent.event)+ if (!usageKey) {+ return Promise.resolve(ok({ ...input, eventUsageRecords: undefined }))+ }+ const { teamId } = input.preparedEvent+ const recordId = analyticsRecordId(input.preparedEvent)+ const eventUsageRecords: EventUsageRecord[] = [{ teamId, usageKey, recordId }]+ // Mirrors the report's enhanced-persons query: the plain billable count plus a `person_mode`+ // filter, so an event billed under its own key is outside both. Reading the mode stored on+ // the event rather than `processPerson` keeps force upgrades counted.+ if (+ usageKey === EVENTS_USAGE_KEY &&+ resolvePersonMode(input.person, input.processPerson ?? false) !== 'propertyless'+ ) {+ eventUsageRecords.push({ teamId, usageKey: 'enhanced_person_events', recordId })+ }+ return Promise.resolve(ok({ ...input, eventUsageRecords }))}}@@ -99,14 +121,15 @@ export function createRecordEventUsageAfterIngestStep<T extends RecordEventUsageT> {return function recordEventUsageAfterIngestStep(input: T): Promise<PipelineResult<T>> {- const record = input.eventUsageRecord- if (record && input.eventUsageBatch) {- input.eventUsageBatch.addAfterAcknowledgements(- input.ingested,- record.teamId,- record.usageKey,- record.recordId- )+ if (input.eventUsageBatch) {+ for (const record of input.eventUsageRecords ?? []) {+ input.eventUsageBatch.addAfterAcknowledgements(+ input.ingested,+ record.teamId,+ record.usageKey,+ record.recordId+ )+ }}return Promise.resolve(ok(input))}diff --git a/nodejs/src/ingestion/common/usage-records/billable-events.test.ts b/nodejs/src/ingestion/common/usage-records/billable-events.test.tsindex 8deeacdee123..2d3d573e28e5 100644--- a/nodejs/src/ingestion/common/usage-records/billable-events.test.ts+++ b/nodejs/src/ingestion/common/usage-records/billable-events.test.ts@@ -1,4 +1,10 @@-import { AI_EVENTS_USAGE_KEY, EVENTS_USAGE_KEY, resolveAiUsageKey, resolveAnalyticsUsageKey } from './billable-events'+import {+ AI_EVENTS_USAGE_KEY,+ EVENTS_USAGE_KEY,+ SURVEY_RESPONSES_USAGE_KEY,+ resolveAiUsageKey,+ resolveAnalyticsUsageKey,+} from './billable-events'describe('usage key resolvers', () => {it.each([@@ -11,7 +17,7 @@ describe('usage key resolvers', () => {['$ai_not_a_real_event', EVENTS_USAGE_KEY],['$feature_flag_called', null],['$experiment_exposure', null],- ['survey sent', null],+ ['survey sent', SURVEY_RESPONSES_USAGE_KEY],['$exception', null],['$llm_prompt_fetched', null],['$conversations_message_sent', null],diff --git a/nodejs/src/ingestion/common/usage-records/billable-events.ts b/nodejs/src/ingestion/common/usage-records/billable-events.tsindex fa498616fd51..0423e422161c 100644--- a/nodejs/src/ingestion/common/usage-records/billable-events.ts+++ b/nodejs/src/ingestion/common/usage-records/billable-events.ts@@ -3,6 +3,7 @@ import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'export const EVENTS_USAGE_KEY = 'events'export const AI_EVENTS_USAGE_KEY = 'ai_events'export const EXCEPTIONS_USAGE_KEY = 'exceptions'+export const SURVEY_RESPONSES_USAGE_KEY = 'survey_responses'/** Null means the event is not billed at all. */export type UsageKeyResolver = (event: string) => string | null@@ -13,7 +14,6 @@ export type UsageKeyResolver = (event: string) => string | nullconst NON_BILLABLE_EVENTS = new Set(['$feature_flag_called','$experiment_exposure',- 'survey sent','survey shown','survey dismissed','$exception',@@ -36,6 +36,9 @@ export const resolveAnalyticsUsageKey: UsageKeyResolver = (event) => {if (AI_EVENT_TYPES.has(event)) {return AI_EVENTS_USAGE_KEY}+ if (event === 'survey sent') {+ return SURVEY_RESPONSES_USAGE_KEY+ }return NON_BILLABLE_EVENTS.has(event) ? null : EVENTS_USAGE_KEY}diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex a9b9201bde46..c64805f30668 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -26,8 +26,7 @@ import {import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PersonRepository } from '~/common/persons/repositories/person-repository'import { instrumentFn } from '~/common/tracing/tracing-utils'-import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'-import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { UsageIngestionConfig, createEventUsageBatchFactory } from '~/common/usage-ingestion'import { PostgresRouter } from '~/common/utils/db/postgres'import {EventIngestionRestrictionManager,@@ -314,7 +313,7 @@ export class IngestionConsumer {EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS: this.config.EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS,},concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,- createEventUsageBatch: this.createEventUsageBatch(),+ createEventUsageBatch: createEventUsageBatchFactory(this.config, 'events'),}const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore: this.personsStore,@@ -400,12 +399,6 @@ export class IngestionConsumer {return new HealthCheckResultOk()}- private createEventUsageBatch(): () => UsageRecordBatch {- const client = createUsageIngestionClient(this.config, 'events')- const isTeamEnabled = usageReportTeamMatcher(this.config)- return () => new UsageRecordBatch(client, { unit: 'events', isTeamEnabled })- }-private runInstrumented<T>(name: string, func: () => Promise<T>): Promise<T> {return instrumentFn<T>(`ingestionConsumer.${name}`, func)}diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.tsindex 9b118fa67399..6655b20de4a0 100644--- a/nodejs/src/ingestion/pipelines/ai/consumer.ts+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts@@ -16,8 +16,7 @@ import { PersonHogConfig } from '~/common/personhog'import { PersonHogClientComponent } from '~/common/personhog/personhog-client-component'import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group-read-repository'import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'-import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'-import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { UsageIngestionConfig, createEventUsageBatchFactory } from '~/common/usage-ingestion'import { PostgresRouter } from '~/common/utils/db/postgres'import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'@@ -171,8 +170,7 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiShared`AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY must be a positive integer, got ${uploadMaxConcurrency}`)}- const usageClient = createUsageIngestionClient(config, 'ai_events')- const usageTeamMatcher = usageReportTeamMatcher(config)+ const createEventUsageBatch = createEventUsageBatchFactory(config, 'ai_events')const aiBlobOffloadConfig = {isTeamEnabled: buildIntegerMatcher(config.AI_BLOB_OFFLOAD_TEAMS, true),@@ -209,8 +207,7 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiSharedtopHog: container.topHog,aiBlobStore: container.aiBlobStore.store,aiBlobOffloadConfig,- createEventUsageBatch: () =>- new UsageRecordBatch(usageClient, { unit: 'events', isTeamEnabled: usageTeamMatcher }),+ createEventUsageBatch,}))}diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.tsindex 36268299a347..60824c61277a 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts@@ -92,7 +92,7 @@ export interface AiIngestionPipelineConfig {topHog: TopHogRegistryaiBlobStore: BlobStore | nullaiBlobOffloadConfig: OffloadAiBlobsConfig- createEventUsageBatch?: () => UsageRecordBatch+ createEventUsageBatch: () => UsageRecordBatch}interface AiIngestionPipelineInput {@@ -140,7 +140,7 @@ export function createAiIngestionPipeline<topHog,aiBlobStore,aiBlobOffloadConfig,- createEventUsageBatch = () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),+ createEventUsageBatch,} = configreturn (diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex e724d2ea8a03..4e74fe87b049 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -82,7 +82,7 @@ export interface JoinedIngestionPipelineConfig {* capacity (consumer under-limits) or stalled stream reads at capacity.*/concurrentBatches: number- createEventUsageBatch?: () => UsageRecordBatch+ createEventUsageBatch: () => UsageRecordBatch}export interface JoinedIngestionPipelineDeps {@@ -131,7 +131,7 @@ export function createJoinedIngestionPipeline<outputs,perDistinctIdOptions,concurrentBatches,- createEventUsageBatch = () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),+ createEventUsageBatch,} = configconst {diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.tsindex b8d592970f2c..a233456c2d87 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.test.ts@@ -8,6 +8,7 @@ import { KafkaConsumer } from '~/common/kafka/consumer/consumer-v1'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'import { PersonReadRepository } from '~/common/persons/repositories/person-repository'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { parseJSON } from '~/common/utils/json-parse'import { UUIDT } from '~/common/utils/utils'import { IngestionTestInfra, createIngestionTestInfra } from '~/tests/helpers/ingestion-e2e'@@ -196,6 +197,7 @@ describe('ErrorTrackingConsumer', () => {cookielessManager: infra.cookielessManager,redisPool: infra.redisPool,personRepository: createMockPersonRepository(),+ createEventUsageBatch: () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),}const consumer = new ErrorTrackingConsumer(config, deps)// Replace Kafka consumer with mock to avoid actual connectionsdiff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.tsindex 24e5acd26dc9..e47f4ca2929b 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts@@ -84,7 +84,7 @@ export interface ErrorTrackingConsumerDeps {cookielessManager: CookielessManagerredisPool: GenericPool<Redis>personRepository: PersonReadRepository- createEventUsageBatch?: () => UsageRecordBatch+ createEventUsageBatch: () => UsageRecordBatch}// Batch processing status - useful for tracking failures (batch sizes already tracked by KafkaConsumer)diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.tsindex e119bcfc78d6..632117c3bc71 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.test.ts@@ -7,6 +7,7 @@ import { TophogOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'import { PersonReadRepository } from '~/common/persons/repositories/person-repository'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { EventIngestionRestrictionManager, RestrictionType } from '~/common/utils/event-ingestion-restrictions'import { parseJSON } from '~/common/utils/json-parse'import { PromiseScheduler } from '~/common/utils/promise-scheduler'@@ -320,6 +321,7 @@ describe('ErrorTrackingPipeline', () => {overflowMode: 'disabled',preservePartitionLocality: false,topHog: mockTopHog,+ createEventUsageBatch: () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),}})diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.tsindex 8f90f7c7eb17..faa04bc8f9a7 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts@@ -102,7 +102,7 @@ export interface ErrorTrackingPipelineConfig {overflowLaneTTLRefreshService?: OverflowRedirectService/** TopHog registry for metrics. */topHog: TopHogRegistry- createEventUsageBatch?: () => UsageRecordBatch+ createEventUsageBatch: () => UsageRecordBatch}/**@@ -146,7 +146,7 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)overflowRedirectService,overflowLaneTTLRefreshService,topHog,- createEventUsageBatch = () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),+ createEventUsageBatch,} = configconst preCymbal = newCommonIngestionPipeline<ErrorTrackingPipelineInput, { message: Message }, OverflowOutput>({diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.tsindex 24ae7a35c4bb..df1fa86bf904 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.test.ts@@ -84,6 +84,11 @@ describe('SessionRecordingIngester', () => {// reach unless a test opts in via overrides.SESSION_RECORDING_MAX_BATCH_AGE_MS: 60 * 60 * 1000,SESSION_RECORDING_MAX_BATCH_SIZE_KB: 1024 * 1024,+ USAGE_INGESTION_ADDR: '',+ USAGE_INGESTION_TLS: false,+ USAGE_INGESTION_TIMEOUT_MS: 5000,+ USAGE_INGESTION_MAX_BATCH_SIZE: 500,+ USAGE_INGESTION_REPORT_TEAMS: '',...configOverrides,}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.tsindex 21d720fdc244..43ceb5821ec8 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts@@ -6,6 +6,8 @@ import { KafkaConsumerV2 } from '~/common/kafka/consumer/consumer-v2'import { DlqOutput, IngestionWarningsOutput, LogEntriesOutput, OverflowOutput, TophogOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { instrumentFn } from '~/common/tracing/tracing-utils'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { PostgresRouter } from '~/common/utils/db/postgres'import {EventIngestionRestrictionManager,@@ -55,6 +57,7 @@ import { SessionTracker } from './sessions/session-tracker'*/export type SessionRecordingIngesterConfig = SessionRecordingConfig &SessionRecordingApiConfig &+ UsageIngestionConfig &Pick<IngestionConsumerConfig,// INGESTION_OVERFLOW_MODE drives force-overflow routing; the rest are for TopHog metrics.@@ -126,6 +129,7 @@ export class SessionRecordingIngester {private readonly keyStore: KeyStoreprivate readonly encryptor: RecordingEncryptorprivate readonly createPipeline: SessionReplayPipelineFactory+ private readonly usageBatch: UsageRecordBatchconstructor(private config: SessionRecordingIngesterConfig,@@ -148,6 +152,10 @@ export class SessionRecordingIngester {this.isDebugLoggingEnabled = buildIntegerMatcher(config.SESSION_RECORDING_DEBUG_PARTITION, true)this.promiseScheduler = new PromiseScheduler()+ this.usageBatch = new UsageRecordBatch(createUsageIngestionClient(config, 'session_replay'), {+ unit: 'recordings',+ isTeamEnabled: usageReportTeamMatcher(config),+ })// The v2 consumer defers the unassign on revoke until in-flight work is drained and the// revoke hook has run, so a revoke can flush the current batch (persisting sessions and@@ -326,7 +334,14 @@ export class SessionRecordingIngester {})await this.batchLock(async () => {logger.info('🔁', 'blob_ingester_consumer_v2 - flushing batch', { batchSize: this.currentBatch.size })- await instrumentFn(`recordingingesterv2.handleEachBatch.flush`, async () => this.currentBatch.flush())+ // Billing has nothing to wait on the batch for, and a usage outage must not stop lag+ // reporting or the batch reset — so it goes out alongside and swallows its own failure.+ await Promise.all([+ instrumentFn(`recordingingesterv2.handleEachBatch.flush`, async () => this.currentBatch.flush()),+ this.usageBatch.flush().catch((error) => {+ logger.warn('⚠️', 'blob_ingester_consumer_v2 - usage flush failed', { error })+ }),+ ])// The flush committed the batch's offsets, so its data is now durably ingested — report lag.// Skipped if the flush above threw, so a failed flush records no premature lag sample.this.lagReporter.flush()@@ -360,6 +375,7 @@ export class SessionRecordingIngester {sessionKeyResolutionMaxConcurrency: this.config.SESSION_RECORDING_KEY_RESOLUTION_MAX_CONCURRENCY,topHog: this.topHog,isDebugLoggingEnabled: this.isDebugLoggingEnabled,+ usageBatch: this.usageBatch,})// Check that the storage backend is healthy before starting the consumerdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.tsindex fff37547f54b..0fd23a2befad 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts@@ -55,10 +55,20 @@ export class SessionRecordingIngesterMetrics {labelNames: ['content_encoding'],})+ private static readonly unbilledNewSession = new Counter({+ name: 'recording_blob_ingestion_v2_unbilled_new_session',+ help: 'New sessions whose first message failed before the usage step, so a later message for the same session bills nothing while the report still counts the recording',+ labelNames: ['reason'],+ })+public static incrementMessageReceived(partition: number): void {this.messageReceived.labels(partition.toString()).inc()}+ public static incrementUnbilledNewSession(reason: string): void {+ this.unbilledNewSession.labels(reason).inc()+ }+public static observeDroppedByRestrictions(count: number): void {this.messagesDroppedByRestrictions.inc(count)recordMessagesDroppedByRestrictions(count)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex 64398252d374..cd9e3cd670b4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -2,6 +2,7 @@ import { Message } from 'node-rdkafka'import { DlqOutput, IngestionWarningsOutput, OverflowOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'@@ -31,6 +32,7 @@ import { createMarkSeenStep } from './session-batch-mark-seen-step'import { createResolveRetentionStep } from './session-batch-resolve-retention-step'import { createTrackAndGateStep } from './session-batch-track-and-gate-step'import { createResolveKeyStep } from './session-resolve-key-step'+import { createRecordSessionUsageStep, trackUnbilledNewSessions } from './session-usage-step'import { createTeamFilterStep } from './team-filter-step'import { createValidateSessionReplayHeadersStep } from './validate-headers-step'@@ -78,6 +80,7 @@ export interface SessionReplayPipelineConfig {topHog: TopHogRegistry/** Debug logging matcher for partition-based debugging. */isDebugLoggingEnabled: ValueMatcher<number>+ usageBatch?: UsageRecordBatch}/**@@ -105,6 +108,7 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)sessionKeyResolutionMaxConcurrency,topHog,isDebugLoggingEnabled,+ usageBatch,} = configconst pipelineConfig: PipelineConfig<OverflowOutput> = {@@ -198,12 +202,14 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)b// Parse message content.pipe(- topHogWrapper(createParseMessageStep(), [- timer('parse_time_ms_by_session_id', (input) => ({- token: input.headers.token ?? 'unknown',- session_id: input.headers.session_id ?? 'unknown',- })),- ])+ trackUnbilledNewSessions(+ topHogWrapper(createParseMessageStep(), [+ timer('parse_time_ms_by_session_id', (input) => ({+ token: input.headers.token ?? 'unknown',+ session_id: input.headers.session_id ?? 'unknown',+ })),+ ])+ ))// Monitor library version and emit warnings for old versions.pipe(createLibVersionMonitorStep())@@ -228,6 +234,7 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)]))+ .pipe(createRecordSessionUsageStep(usageBatch))).gather())diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.tsnew file mode 100644index 000000000000..fb2bc9b86547--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.test.ts@@ -0,0 +1,117 @@+import { DateTime } from 'luxon'+import { register } from 'prom-client'++import { UsageIngestionClient, UsageRecordInput } from '~/common/usage-ingestion/client'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { drop, ok } from '~/ingestion/framework/results'++import { ParsedMessageData } from './kafka/types'+import { Recordable, SessionReplayHeaders } from './pipeline-types'+import { createRecordSessionUsageStep, trackUnbilledNewSessions } from './session-usage-step'+import { TeamForReplay } from './teams/types'++type SessionUsageValue = Recordable<{+ team: TeamForReplay+ headers: SessionReplayHeaders+ parsedMessage: ParsedMessageData+ isNewSession: boolean+}>++describe('createRecordSessionUsageStep', () => {+ let ingested: UsageRecordInput[]+ let usageBatch: UsageRecordBatch++ beforeEach(() => {+ ingested = []+ const client = {+ ingest: jest.fn((records: UsageRecordInput[]) => {+ ingested.push(...records)+ return Promise.resolve()+ }),+ } as unknown as UsageIngestionClient+ usageBatch = new UsageRecordBatch(client, { unit: 'recordings', isTeamEnabled: () => true })+ })++ function buildValue(+ snapshotSource: string | null,+ snapshotLibrary: string | null,+ isNewSession: boolean+ ): SessionUsageValue {+ return {+ team: { teamId: 42, consoleLogIngestionEnabled: false, aiTrainingOptedIn: false },+ headers: { token: 'token', session_id: 'session-1', distinct_id: 'distinct-1' },+ parsedMessage: {+ distinct_id: 'distinct-1',+ session_id: 'session-1',+ token: 'token',+ eventsByWindowId: { window1: [] },+ eventsRange: { start: DateTime.fromMillis(0), end: DateTime.fromMillis(0) },+ snapshot_source: snapshotSource,+ snapshot_library: snapshotLibrary,+ metadata: { partition: 0, topic: 'test-topic', rawSize: 0, offset: 0, timestamp: 0 },+ },+ isNewSession,+ status: 'allowed',+ sessionKey: {+ plaintextKey: Buffer.alloc(0),+ encryptedKey: Buffer.alloc(0),+ sessionState: 'ciphertext',+ },+ }+ }++ async function record(+ snapshotSource: string | null,+ snapshotLibrary: string | null,+ isNewSession = true+ ): Promise<string[]> {+ const step = createRecordSessionUsageStep(usageBatch)+ await step(buildValue(snapshotSource, snapshotLibrary, isNewSession))++ await usageBatch.flush()+ return ingested.map((record) => record.usageKey)+ }++ it.each([+ ['web', 'posthog-js', ['session_replay_recordings']],+ ['mobile', 'posthog-ios', ['mobile_replay_recordings']],+ ['mobile', 'posthog-flutter', ['mobile_replay_recordings']],+ // The report bills mobile replay only from four named libraries. The meter reads the+ // source instead, so a mobile recording bills whatever library it names.+ ['mobile', 'posthog-python', ['mobile_replay_recordings']],+ ['mobile', null, ['mobile_replay_recordings']],+ // Nothing validates the source, so anything but 'mobile' bills as web rather than for free.+ ['desktop', 'posthog-js', ['session_replay_recordings']],+ [null, null, ['session_replay_recordings']],+ ])('bills a %s session from %s under %j', async (source, library, expectedUsageKeys) => {+ expect(await record(source, library)).toEqual(expectedUsageKeys)+ })++ it('bills nothing for a session already seen in this batch', async () => {+ expect(await record('web', 'posthog-js', false)).toEqual([])+ })++ describe('trackUnbilledNewSessions', () => {+ async function unbilledCount(): Promise<number> {+ const metric = register.getSingleMetric('recording_blob_ingestion_v2_unbilled_new_session')!+ const data = (await metric.get()) as { values: { value: number }[] }+ return data.values.reduce((total, entry) => total + entry.value, 0)+ }++ it.each([+ ['counts a new session whose message fails', true, false, 1],+ ['counts nothing for a session already seen', false, false, 0],+ ['counts nothing for a new session that parses', true, true, 0],+ ])('%s', async (_name, isNewSession, succeeds, expectedIncrease) => {+ const value = buildValue('web', 'posthog-js', isNewSession)+ const before = await unbilledCount()+ const step = trackUnbilledNewSessions(() =>+ Promise.resolve(succeeds ? ok(value) : drop<typeof value>('message_contained_no_valid_rrweb_events'))+ )++ await step(value)++ expect(await unbilledCount()).toEqual(before + expectedIncrease)+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.tsnew file mode 100644index 000000000000..ab32b27e740e--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-usage-step.ts@@ -0,0 +1,63 @@+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { PipelineResult, isOkResult, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { ParsedMessageData } from './kafka/types'+import { SessionRecordingIngesterMetrics } from './metrics'+import { NewSessionFlag, Recordable, SessionReplayHeaders } from './pipeline-types'+import { TeamForReplay } from './teams/types'++type SessionUsageInput = {+ team: TeamForReplay+ headers: SessionReplayHeaders+ parsedMessage: ParsedMessageData+} & NewSessionFlag++/**+ * The meter this session bills under. Every session bills exactly one, so no `snapshot_source`+ * buys a free recording.+ *+ * Anything other than `mobile` is a web recording, including a value no SDK sends. Nothing between+ * the SDK and here validates the field, so matching `web` exactly would let any other string bill+ * nowhere. The report does match it exactly, and bills a mobile recording only from four named+ * libraries, so it bills neither meter for a session outside those values. Those are holes on its+ * side rather than a contract to copy.+ *+ * The meter reads the first message processed for the session. The report instead reads the+ * earliest snapshot's metadata, so the two disagree if one session's messages disagree with each+ * other about their source, which no single client does.+ */+function billableMeter(snapshotSource: string | null): string {+ return snapshotSource === 'mobile' ? 'mobile_replay_recordings' : 'session_replay_recordings'+}++export function createRecordSessionUsageStep<T extends SessionUsageInput>(+ usageBatch?: UsageRecordBatch+): ProcessingStep<Recordable<T>, Recordable<T>> {+ return function recordSessionUsage(value): Promise<PipelineResult<Recordable<T>>> {+ if (value.isNewSession) {+ const meter = billableMeter(value.parsedMessage.snapshot_source)+ usageBatch?.add(value.team.teamId, meter, value.headers.session_id)+ }+ return Promise.resolve(ok(value))+ }+}++/**+ * Counts the new sessions that lose their flag before they can bill. The pipeline marks a session+ * seen before this step's message is parsed, so a first message that fails takes the flag with it:+ * a later valid message for the same session bills nothing, while the report still counts the+ * recording it produced. Marking later is not free — the mark sits after key resolution so a+ * recording is never written in cleartext — so measure how often this happens before paying for it.+ */+export function trackUnbilledNewSessions<T extends NewSessionFlag, U>(+ step: ProcessingStep<T, U>+): ProcessingStep<T, U> {+ return async function trackUnbilledNewSession(value): Promise<PipelineResult<U>> {+ const result = await step(value)+ if (value.isNewSession && !isOkResult(result)) {+ SessionRecordingIngesterMetrics.incrementUnbilledNewSession(result.reason)+ }+ return result+ }+}diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex 6325ee24c658..73b0394a1b4c 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -16,6 +16,7 @@ import { KAFKA_APP_METRICS_2, KAFKA_LOGS_CLICKHOUSE, KAFKA_LOGS_INGESTION_DLQ }import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { parseJSON } from '~/common/utils/json-parse'@@ -228,6 +229,7 @@ describe('LogsIngestionConsumer', () => {'test'),}),+ usageBatch: new UsageRecordBatch(null, { unit: 'bytes', isTeamEnabled: () => false }),...depsPartial,},overrides@@ -2064,6 +2066,7 @@ describe('LogsIngestionConsumer', () => {'test'),}),+ usageBatch: new UsageRecordBatch(null, { unit: 'bytes', isTeamEnabled: () => false }),})tracesConsumer['kafkaConsumer'] = {diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex 4013e35ae179..c42625cabf15 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -11,9 +11,11 @@ import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'import { QuotaLimiting, QuotaResource } from '~/common/services/quota-limiting.service'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { isDevEnv } from '~/common/utils/env-utils'import { logger } from '~/common/utils/logger'import { TeamManager } from '~/common/utils/team-manager'+import { UUID7 } from '~/common/utils/utils'import type { LogsSettings } from '~/types'import { HealthCheckResult, PluginServerService } from '~/types'@@ -70,6 +72,7 @@ export interface LogsIngestionConsumerDeps {* directly.*/outputs: IngestionOutputs<LogsOutput | LogsDlqOutput | AppMetricsOutput>+ usageBatch: UsageRecordBatch}/** Ingestion default when `logs_settings.retention_days` is unset; must be in `TeamSerializer.VALID_RETENTION_DAYS`. */@@ -1064,14 +1067,31 @@ export class LogsIngestionConsumer {if (retentionMetric) {this.queueUsageMetric(teamId, retentionMetric, stats.bytesAllowed)}+ const source = this.appSource === 'traces' ? 'apm_traces' : 'logs'+ // These records are per-flush aggregates, not one per billed thing, so there is no+ // stable identity to reproduce. A fresh ID per flush is what keeps two pods flushing+ // the same team from colliding and collapsing one flush's quantity away.+ const flushId = new UUID7().toString()+ this.deps.usageBatch.add(teamId, `${source}_bytes`, flushId, stats.bytesAllowed, 'bytes')+ this.deps.usageBatch.add(+ teamId,+ source === 'apm_traces' ? 'apm_traces_spans' : 'logs_records',+ flushId,+ stats.recordsAllowed,+ 'records'+ )}- // Best-effort: don't let metric failures block ingestion- try {- await this.appMetricsAggregator.flush()- } catch (error) {- logger.error('🔴', 'Failed to emit usage metrics - billing data may be lost', { error })- }+ // Best-effort, and independent of each other: neither failing may block ingestion or skip+ // the other, and nothing downstream reads either result, so they go out together.+ await Promise.all([+ this.appMetricsAggregator.flush().catch((error) => {+ logger.error('🔴', 'Failed to emit usage metrics - billing data may be lost', { error })+ }),+ this.deps.usageBatch.flush().catch((error) => {+ logger.error('🔴', 'Failed to emit usage records - billing data may be lost', { error })+ }),+ ])}private queueUsageMetric(teamId: number, metricName: string, count: number): void {diff --git a/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.ts b/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.tsindex da35540ecd2e..734db9eba889 100644--- a/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.ts+++ b/nodejs/src/logs/logs-ingestion-thread-relief.serial.test.ts@@ -8,6 +8,7 @@ import { KAFKA_APP_METRICS_2, KAFKA_LOGS_CLICKHOUSE, KAFKA_LOGS_INGESTION_DLQ }import { APP_METRICS_OUTPUT, AppMetricsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { closeHub, createHub } from '~/common/utils/db/hub'import { PostgresUse } from '~/common/utils/db/postgres'import { createTestTeamFixture } from '~/tests/helpers/sql'@@ -116,6 +117,7 @@ describe('LogsIngestionConsumer thread relief', () => {'test'),}),+ usageBatch: new UsageRecordBatch(null, { unit: 'bytes', isTeamEnabled: () => false }),})consumer['kafkaConsumer'] = {connect: jest.fn(),diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.tsindex 9fdcabd5866c..83a1f6574c90 100644--- a/nodejs/src/servers/error-tracking-server.ts+++ b/nodejs/src/servers/error-tracking-server.ts@@ -10,8 +10,7 @@ import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { PersonHogConfig, createPersonHogClient } from '~/common/personhog'import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group-read-repository'import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'-import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'-import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { UsageIngestionConfig, createEventUsageBatchFactory } from '~/common/usage-ingestion'import { ServerCommands } from '~/common/utils/commands'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'@@ -197,9 +196,7 @@ export class ErrorTrackingServer implements NodeServer {// 3. Error tracking consumerconst serviceLoaders: (() => Promise<PluginServerService>)[] = []- // One client for the process: the batch factory runs per batch, and each client owns a transport.- const usageClient = createUsageIngestionClient(this.config, 'exceptions')- const usageTeamMatcher = usageReportTeamMatcher(this.config)+ const createEventUsageBatch = createEventUsageBatchFactory(this.config, 'exceptions')serviceLoaders.push(async () => {const consumer = new ErrorTrackingConsumer(@@ -229,8 +226,7 @@ export class ErrorTrackingServer implements NodeServer {cookielessManager: this.cookielessManager!,redisPool: this.redisPool!,personRepository,- createEventUsageBatch: () =>- new UsageRecordBatch(usageClient, { unit: 'events', isTeamEnabled: usageTeamMatcher }),+ createEventUsageBatch,})await consumer.start()diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 31e4e9fdd90f..3411be1184fe 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -15,6 +15,7 @@ import { PersonHogClient } from '~/common/personhog/client'import { createIdentityClients } from '~/common/personhog/identity-clients'import { PersonHogPersonWriteRepository } from '~/common/personhog/personhog-person-write-repository'import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'+import { UsageIngestionConfig, createEventUsageBatchFactory } from '~/common/usage-ingestion'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'@@ -107,6 +108,7 @@ export type IngestionApiServerConfig = BaseServerConfig &RedisConnectionsConfig &KafkaConsumerBaseConfig &PersonHogConfig &+ UsageIngestionConfig &Pick<CommonConfig,| 'LOG_LEVEL'@@ -418,6 +420,7 @@ export class IngestionApiServer implements NodeServer {EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS: this.config.EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS,},concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,+ createEventUsageBatch: createEventUsageBatchFactory(this.config, 'events'),}const eventFilterManagerStarted = await new EventFilterManagerComponent(this.postgres).start()const featureFlagCalledDedupService = createFeatureFlagCalledDedupService(diff --git a/nodejs/src/servers/ingestion-logs-server.ts b/nodejs/src/servers/ingestion-logs-server.tsindex cd75b7be13e1..74394d5a239d 100644--- a/nodejs/src/servers/ingestion-logs-server.ts+++ b/nodejs/src/servers/ingestion-logs-server.ts@@ -2,6 +2,8 @@ import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'import { createPosthogRedisConnectionConfig } from '~/common/config/redis-pools'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { logger } from '~/common/utils/logger'@@ -55,6 +57,7 @@ export type IngestionLogsServerConfig = BaseServerConfig &KafkaBrokerConfig &DatabaseConnectionConfig &RedisConnectionsConfig &+ UsageIngestionConfig &Pick<CommonConfig,| 'LOG_LEVEL'@@ -154,6 +157,10 @@ export class IngestionLogsServer implements NodeServer {const serviceLoaders: (() => Promise<PluginServerService>)[] = []serviceLoaders.push(async () => {+ const usageBatch = new UsageRecordBatch(createUsageIngestionClient(this.config, 'logs'), {+ unit: 'bytes',+ isTeamEnabled: usageReportTeamMatcher(this.config),+ })const consumer = new LogsIngestionConsumer(this.config, {teamManager,quotaLimiting,@@ -163,6 +170,7 @@ export class IngestionLogsServer implements NodeServer {metricsEmitter,logsTransformer,retentionRulesCache,+ usageBatch,})await consumer.start()return consumer.servicediff --git a/nodejs/src/servers/ingestion-traces-server.ts b/nodejs/src/servers/ingestion-traces-server.tsindex 97bdd53a6dc2..d66bdfeb5f10 100644--- a/nodejs/src/servers/ingestion-traces-server.ts+++ b/nodejs/src/servers/ingestion-traces-server.ts@@ -2,6 +2,8 @@ import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'import { createPosthogRedisConnectionConfig } from '~/common/config/redis-pools'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { QuotaLimiting } from '~/common/services/quota-limiting.service'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'import { logger } from '~/common/utils/logger'@@ -49,6 +51,7 @@ export type IngestionTracesServerConfig = BaseServerConfig &KafkaBrokerConfig &DatabaseConnectionConfig &RedisConnectionsConfig &+ UsageIngestionConfig &Pick<CommonConfig, 'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'CLOUD_DEPLOYMENT' | 'HEALTHCHECK_MAX_STALE_SECONDS'>export class IngestionTracesServer implements NodeServer {@@ -110,10 +113,15 @@ export class IngestionTracesServer implements NodeServer {const serviceLoaders: (() => Promise<PluginServerService>)[] = []serviceLoaders.push(async () => {+ const usageBatch = new UsageRecordBatch(createUsageIngestionClient(this.config, 'apm_traces'), {+ unit: 'bytes',+ isTeamEnabled: usageReportTeamMatcher(this.config),+ })const consumer = new TracesIngestionConsumer(this.config, {teamManager,quotaLimiting,outputs,+ usageBatch,})await consumer.start()return consumer.service