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(ingestion): optimize group batch store writes and reads (#69946)

José Sequeirac2139a854368
diff --git a/nodejs/src/common/groups/group-type-manager.test.ts b/nodejs/src/common/groups/group-type-manager.test.ts
index 71baa7a24ce5..9405e54105e6 100644
--- a/nodejs/src/common/groups/group-type-manager.test.ts
+++ b/nodejs/src/common/groups/group-type-manager.test.ts
@@ -134,6 +134,23 @@ describe('GroupTypeManager()', () => {
})
})
+ describe('lookupGroupTypeIndex()', () => {
+ it.each([
+ ['an existing group type', 'g0', 0],
+ ['an unknown group type', 'brand-new', null],
+ // Inherited object properties must not resolve to junk values that
+ // poison downstream SQL parameters (and crash prefetch workers).
+ ['__proto__', '__proto__', null],
+ ['constructor', 'constructor', null],
+ ])('resolves %s without creating a mapping', async (_name, groupType, expected) => {
+ await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'g0', 0, TEST_TIMESTAMP)
+ jest.mocked(hub.groupRepository.insertGroupType).mockClear()
+
+ expect(await groupTypeManager.lookupGroupTypeIndex(2 as ProjectId, groupType)).toEqual(expected)
+ expect(hub.groupRepository.insertGroupType).not.toHaveBeenCalled()
+ })
+ })
+
describe('fetchGroupTypeIndex()', () => {
it('fetches an already existing value', async () => {
await hub.groupRepository.insertGroupType(2, 2 as ProjectId, 'foo', 0, TEST_TIMESTAMP)
diff --git a/nodejs/src/common/groups/group-type-manager.ts b/nodejs/src/common/groups/group-type-manager.ts
index bd5343577874..dacc0423bc13 100644
--- a/nodejs/src/common/groups/group-type-manager.ts
+++ b/nodejs/src/common/groups/group-type-manager.ts
@@ -55,17 +55,31 @@ export class GroupTypeManager {
return (await this.loader.get(projectId.toString())) ?? {}
}
+ /**
+ * Resolve a group type to its column index from the cached mapping only — never creates a
+ * mapping. Own-property + type guarded: the mapping is a plain object, so an
+ * attacker-supplied name like "__proto__" or "constructor" would otherwise resolve to an
+ * inherited non-numeric value and poison downstream SQL parameters.
+ */
+ public async lookupGroupTypeIndex(projectId: ProjectId, groupType: string): Promise<GroupTypeIndex | null> {
+ const groupTypes = await this.fetchGroupTypes(projectId)
+ const groupTypeIndex = Object.hasOwn(groupTypes, groupType) ? groupTypes[groupType] : undefined
+ return typeof groupTypeIndex === 'number' ? groupTypeIndex : null
+ }
+
public async fetchGroupTypeIndex(
teamId: TeamId,
projectId: ProjectId,
groupType: string,
eventTimestamp: DateTime
): Promise<GroupTypeIndex | null> {
- const groupTypes = await this.fetchGroupTypes(projectId)
- if (groupType in groupTypes) {
- return groupTypes[groupType]
+ const existingIndex = await this.lookupGroupTypeIndex(projectId, groupType)
+ if (existingIndex !== null) {
+ return existingIndex
}
+ const groupTypes = await this.fetchGroupTypes(projectId)
+
const usedIndexes = new Set(Object.values(groupTypes))
if (usedIndexes.size >= MAX_GROUP_TYPES_PER_TEAM) {
return null
diff --git a/nodejs/src/common/groups/repositories/clickhouse-group-repository.ts b/nodejs/src/common/groups/repositories/clickhouse-group-repository.ts
index e42fa070fedc..47b4a975eaf4 100644
--- a/nodejs/src/common/groups/repositories/clickhouse-group-repository.ts
+++ b/nodejs/src/common/groups/repositories/clickhouse-group-repository.ts
@@ -6,9 +6,37 @@ import { castTimestampOrNow } from '~/common/utils/utils'
import { Properties } from '~/plugin-scaffold'
import { GroupTypeIndex, TeamId, TimestampFormat } from '~/types'
+export type GroupClickhouseMessage = {
+ output: GroupsOutput
+ value: Buffer
+}
+
export class ClickhouseGroupRepository {
constructor(private outputs: IngestionOutputs<GroupsOutput>) {}
+ public buildUpsertMessage(
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string,
+ properties: Properties,
+ createdAt: DateTime,
+ version: number
+ ): GroupClickhouseMessage {
+ return {
+ output: GROUPS_OUTPUT,
+ value: Buffer.from(
+ JSON.stringify({
+ group_type_index: groupTypeIndex,
+ group_key: groupKey,
+ team_id: teamId,
+ group_properties: JSON.stringify(properties),
+ created_at: castTimestampOrNow(createdAt, TimestampFormat.ClickHouseSecondPrecision),
+ version,
+ })
+ ),
+ }
+ }
+
public async upsertGroup(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
@@ -17,18 +45,10 @@ export class ClickhouseGroupRepository {
createdAt: DateTime,
version: number
): Promise<void> {
+ const message = this.buildUpsertMessage(teamId, groupTypeIndex, groupKey, properties, createdAt, version)
await this.outputs.queueMessages(GROUPS_OUTPUT, [
{
- value: Buffer.from(
- JSON.stringify({
- group_type_index: groupTypeIndex,
- group_key: groupKey,
- team_id: teamId,
- group_properties: JSON.stringify(properties),
- created_at: castTimestampOrNow(createdAt, TimestampFormat.ClickHouseSecondPrecision),
- version,
- })
- ),
+ value: message.value,
teamId,
},
])
diff --git a/nodejs/src/common/groups/repositories/group-repository-transaction.interface.ts b/nodejs/src/common/groups/repositories/group-repository-transaction.interface.ts
index 72ba37aeec06..f9e330032f96 100644
--- a/nodejs/src/common/groups/repositories/group-repository-transaction.interface.ts
+++ b/nodejs/src/common/groups/repositories/group-repository-transaction.interface.ts
@@ -3,6 +3,8 @@ import { DateTime } from 'luxon'
import { Properties } from '~/plugin-scaffold'
import { Group, GroupTypeIndex, ProjectId, PropertiesLastOperation, PropertiesLastUpdatedAt, TeamId } from '~/types'
+import { GroupKey } from './group-repository.interface'
+
export interface GroupRepositoryTransaction {
fetchGroup(
teamId: TeamId,
@@ -11,11 +13,7 @@ export interface GroupRepositoryTransaction {
options?: { forUpdate?: boolean; useReadReplica?: boolean }
): Promise<Group | undefined>
- fetchGroupsByKeys(
- teamIds: TeamId[],
- groupTypeIndexes: GroupTypeIndex[],
- groupKeys: string[]
- ): Promise<
+ fetchGroupsByKeys(keys: GroupKey[]): Promise<
{
team_id: TeamId
group_type_index: GroupTypeIndex
diff --git a/nodejs/src/common/groups/repositories/group-repository.interface.ts b/nodejs/src/common/groups/repositories/group-repository.interface.ts
index 7494cd23bb80..a82846706aac 100644
--- a/nodejs/src/common/groups/repositories/group-repository.interface.ts
+++ b/nodejs/src/common/groups/repositories/group-repository.interface.ts
@@ -37,6 +37,26 @@ export interface GroupReadRepository {
): Promise<Record<string, { group_type: string; group_type_index: GroupTypeIndex }[]>>
}
+/** Identity of a single group row: (team_id, group_type_index, group_key). */
+export interface GroupKey {
+ teamId: TeamId
+ groupTypeIndex: GroupTypeIndex
+ groupKey: string
+}
+
+/**
+ * A batched, merge-semantics group update: `propertiesToSet` is applied on top
+ * of the stored `group_properties` server-side (jsonb `||`), so concurrent
+ * writers can't lose each other's keys and no version assertion is needed.
+ */
+export interface GroupPropertiesToSetUpdate {
+ teamId: TeamId
+ groupTypeIndex: GroupTypeIndex
+ groupKey: string
+ propertiesToSet: Properties
+ createdAt: DateTime
+}
+
/**
* Full group repository with read and write operations. Used by the
* ingestion pipeline which creates, updates, and manages groups.
@@ -51,9 +71,7 @@ export interface GroupRepository {
): Promise<Group | undefined>
fetchGroupsByKeys(
- teamIds: TeamId[],
- groupTypeIndexes: GroupTypeIndex[],
- groupKeys: string[],
+ keys: GroupKey[],
callerTag?: string
): Promise<
{
@@ -61,9 +79,18 @@ export interface GroupRepository {
group_type_index: GroupTypeIndex
group_key: string
group_properties: Record<string, any>
+ created_at: DateTime
+ version: number
}[]
>
+ /**
+ * Applies all updates in a single statement and returns the updated rows.
+ * Rows whose group doesn't exist are absent from the result — callers
+ * handle those individually (typically by creating the group).
+ */
+ updateGroupsBatch(updates: GroupPropertiesToSetUpdate[]): Promise<Group[]>
+
insertGroup(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
diff --git a/nodejs/src/common/groups/repositories/postgres-group-repository-transaction.ts b/nodejs/src/common/groups/repositories/postgres-group-repository-transaction.ts
index 5290abcd0db4..5893f03c16e3 100644
--- a/nodejs/src/common/groups/repositories/postgres-group-repository-transaction.ts
+++ b/nodejs/src/common/groups/repositories/postgres-group-repository-transaction.ts
@@ -5,6 +5,7 @@ import { Properties } from '~/plugin-scaffold'
import { Group, GroupTypeIndex, ProjectId, PropertiesLastOperation, PropertiesLastUpdatedAt, TeamId } from '~/types'
import { GroupRepositoryTransaction } from './group-repository-transaction.interface'
+import { GroupKey } from './group-repository.interface'
import { RawPostgresGroupRepository } from './raw-postgres-group-repository.interface'
export class PostgresGroupRepositoryTransaction implements GroupRepositoryTransaction {
@@ -22,11 +23,7 @@ export class PostgresGroupRepositoryTransaction implements GroupRepositoryTransa
return await this.repository.fetchGroup(teamId, groupTypeIndex, groupKey, options, this.tx)
}
- async fetchGroupsByKeys(
- teamIds: TeamId[],
- groupTypeIndexes: GroupTypeIndex[],
- groupKeys: string[]
- ): Promise<
+ async fetchGroupsByKeys(keys: GroupKey[]): Promise<
{
team_id: TeamId
group_type_index: GroupTypeIndex
@@ -34,7 +31,7 @@ export class PostgresGroupRepositoryTransaction implements GroupRepositoryTransa
group_properties: Record<string, any>
}[]
> {
- return await this.repository.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, undefined, this.tx)
+ return await this.repository.fetchGroupsByKeys(keys, undefined, this.tx)
}
async insertGroup(
diff --git a/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts b/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts
index df2d5c121d87..3cbb6e5b0aec 100644
--- a/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts
+++ b/nodejs/src/common/groups/repositories/postgres-group-repository.integration.test.ts
@@ -860,6 +860,56 @@ describe('PostgresGroupRepository Integration', () => {
})
})
+ describe('updateGroupsBatch', () => {
+ it('merges properties server-side, backdates created_at, bumps version, and omits missing groups', async () => {
+ await insertTestTeam(teamId)
+ await insertTestGroup({ group_key: 'group-a', group_properties: JSON.stringify({ name: 'A', keep: 1 }) })
+ await insertTestGroup({ group_key: 'group-b', group_properties: JSON.stringify({ name: 'B' }), version: 3 })
+
+ const earlierCreatedAt = createdAt.minus({ days: 1 })
+ const result = await repository.updateGroupsBatch([
+ {
+ teamId,
+ groupTypeIndex,
+ groupKey: 'group-a',
+ propertiesToSet: { name: 'A2', added: true },
+ createdAt: earlierCreatedAt,
+ },
+ {
+ teamId,
+ groupTypeIndex,
+ groupKey: 'group-b',
+ propertiesToSet: { plan: 'scale' },
+ createdAt: createdAt.plus({ days: 1 }),
+ },
+ {
+ teamId,
+ groupTypeIndex,
+ groupKey: 'does-not-exist',
+ propertiesToSet: { x: 1 },
+ createdAt,
+ },
+ ])
+
+ expect(result).toHaveLength(2)
+ const byKey = new Map(result.map((g) => [g.group_key, g]))
+
+ // Set keys win, untouched keys survive, version bumps, created_at backdates.
+ expect(byKey.get('group-a')).toMatchObject({
+ group_properties: { name: 'A2', keep: 1, added: true },
+ created_at: earlierCreatedAt,
+ version: 2,
+ })
+ // A later createdAt never moves created_at forward.
+ expect(byKey.get('group-b')).toMatchObject({
+ group_properties: { name: 'B', plan: 'scale' },
+ created_at: createdAt,
+ version: 4,
+ })
+ expect(byKey.has('does-not-exist')).toBe(false)
+ })
+ })
+
describe('inTransaction', () => {
it('should execute operations within a transaction', async () => {
await insertTestTeam(teamId)
@@ -1831,22 +1881,7 @@ describe('PostgresGroupRepository Integration', () => {
})
it('should return empty array for empty inputs', async () => {
- expect(await repository.fetchGroupsByKeys([], [], [])).toEqual([])
- })
-
- it('should throw error for mismatched array lengths', async () => {
- await expect(repository.fetchGroupsByKeys([teamId], [], [])).rejects.toThrow(
- 'fetchGroupsByKeys: array lengths must match'
- )
- await expect(repository.fetchGroupsByKeys([], [0 as GroupTypeIndex], [])).rejects.toThrow(
- 'fetchGroupsByKeys: array lengths must match'
- )
- await expect(repository.fetchGroupsByKeys([], [], ['key1'])).rejects.toThrow(
- 'fetchGroupsByKeys: array lengths must match'
- )
- await expect(
- repository.fetchGroupsByKeys([teamId, teamId], [0 as GroupTypeIndex], ['key1'])
- ).rejects.toThrow('fetchGroupsByKeys: array lengths must match')
+ expect(await repository.fetchGroupsByKeys([])).toEqual([])
})
it('should fetch single group by keys', async () => {
@@ -1863,7 +1898,9 @@ describe('PostgresGroupRepository Integration', () => {
propertiesLastOperation
)
- const result = await repository.fetchGroupsByKeys([teamId], [0 as GroupTypeIndex], ['posthog'])
+ const result = await repository.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'posthog' },
+ ])
expect(result).toHaveLength(1)
expect(result[0]).toEqual({
@@ -1871,6 +1908,8 @@ describe('PostgresGroupRepository Integration', () => {
group_type_index: 0,
group_key: 'posthog',
group_properties: groupProperties,
+ created_at: createdAt,
+ version: 1,
})
})
@@ -1884,11 +1923,11 @@ describe('PostgresGroupRepository Integration', () => {
await repository.insertGroup(teamId, 0 as GroupTypeIndex, 'acme', company2Props, createdAt, {}, {})
await repository.insertGroup(teamId, 1 as GroupTypeIndex, 'eng-team', org1Props, createdAt, {}, {})
- const result = await repository.fetchGroupsByKeys(
- [teamId, teamId, teamId],
- [0 as GroupTypeIndex, 0 as GroupTypeIndex, 1 as GroupTypeIndex],
- ['posthog', 'acme', 'eng-team']
- )
+ const result = await repository.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'posthog' },
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'acme' },
+ { teamId, groupTypeIndex: 1 as GroupTypeIndex, groupKey: 'eng-team' },
+ ])
expect(result).toHaveLength(3)
expect(result).toEqual(
@@ -1898,25 +1937,33 @@ describe('PostgresGroupRepository Integration', () => {
group_type_index: 0,
group_key: 'posthog',
group_properties: company1Props,
+ created_at: createdAt,
+ version: 1,
},
{
team_id: teamId,
group_type_index: 0,
group_key: 'acme',
group_properties: company2Props,
+ created_at: createdAt,
+ version: 1,
},
{
team_id: teamId,
group_type_index: 1,
group_key: 'eng-team',
group_properties: org1Props,
+ created_at: createdAt,
+ version: 1,
},
])
)
})
it('should handle non-existent groups', async () => {
- const result = await repository.fetchGroupsByKeys([teamId], [0 as GroupTypeIndex], ['non-existent'])
+ const result = await repository.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'non-existent' },
+ ])
expect(result).toEqual([])
})
@@ -1927,11 +1974,10 @@ describe('PostgresGroupRepository Integration', () => {
// Insert only one group
await repository.insertGroup(teamId, 0 as GroupTypeIndex, 'posthog', groupProperties, createdAt, {}, {})
- const result = await repository.fetchGroupsByKeys(
- [teamId, teamId],
- [0 as GroupTypeIndex, 0 as GroupTypeIndex],
- ['posthog', 'non-existent']
- )
+ const result = await repository.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'posthog' },
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'non-existent' },
+ ])
expect(result).toHaveLength(1)
expect(result[0]).toEqual({
@@ -1939,6 +1985,8 @@ describe('PostgresGroupRepository Integration', () => {
group_type_index: 0,
group_key: 'posthog',
group_properties: groupProperties,
+ created_at: createdAt,
+ version: 1,
})
})
@@ -1954,11 +2002,10 @@ describe('PostgresGroupRepository Integration', () => {
await repository.insertGroup(teamId, 0 as GroupTypeIndex, 'company1', team1Props, createdAt, {}, {})
await repository.insertGroup(localTeamId2, 0 as GroupTypeIndex, 'company2', team2Props, createdAt, {}, {})
- const result = await repository.fetchGroupsByKeys(
- [teamId, localTeamId2],
- [0 as GroupTypeIndex, 0 as GroupTypeIndex],
- ['company1', 'company2']
- )
+ const result = await repository.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'company1' },
+ { teamId: localTeamId2, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'company2' },
+ ])
expect(result).toHaveLength(2)
expect(result).toEqual(
@@ -1968,12 +2015,16 @@ describe('PostgresGroupRepository Integration', () => {
group_type_index: 0,
group_key: 'company1',
group_properties: team1Props,
+ created_at: createdAt,
+ version: 1,
},
{
team_id: localTeamId2,
group_type_index: 0,
group_key: 'company2',
group_properties: team2Props,
+ created_at: createdAt,
+ version: 1,
},
])
)
@@ -1984,7 +2035,9 @@ describe('PostgresGroupRepository Integration', () => {
await repository.insertGroup(teamId, 0 as GroupTypeIndex, 'posthog', groupProperties, createdAt, {}, {})
- const result = await repository.fetchGroupsByKeys([teamId], [0 as GroupTypeIndex], ['posthog'])
+ const result = await repository.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'posthog' },
+ ])
// Verify types are correctly cast (will fail at compile time if not)
const teamIdResult: TeamId = result[0].team_id
diff --git a/nodejs/src/common/groups/repositories/postgres-group-repository.ts b/nodejs/src/common/groups/repositories/postgres-group-repository.ts
index 893fe6c818ef..a20004f016e5 100644
--- a/nodejs/src/common/groups/repositories/postgres-group-repository.ts
+++ b/nodejs/src/common/groups/repositories/postgres-group-repository.ts
@@ -16,7 +16,7 @@ import {
} from '~/types'
import { GroupRepositoryTransaction } from './group-repository-transaction.interface'
-import { GroupRepository } from './group-repository.interface'
+import { GroupKey, GroupPropertiesToSetUpdate, GroupRepository } from './group-repository.interface'
import { PostgresGroupRepositoryTransaction } from './postgres-group-repository-transaction'
import { RawPostgresGroupRepository } from './raw-postgres-group-repository.interface'
@@ -62,9 +62,7 @@ export class PostgresGroupRepository
}
async fetchGroupsByKeys(
- teamIds: TeamId[],
- groupTypeIndexes: GroupTypeIndex[],
- groupKeys: string[],
+ keys: GroupKey[],
callerTag?: string,
tx?: TransactionClient
): Promise<
@@ -73,16 +71,11 @@ export class PostgresGroupRepository
group_type_index: GroupTypeIndex
group_key: string
group_properties: Record<string, any>
+ created_at: DateTime
+ version: number
}[]
> {
- // All arrays must have the same length since they represent tuples
- if (teamIds.length !== groupTypeIndexes.length || teamIds.length !== groupKeys.length) {
- throw new Error(
- `fetchGroupsByKeys: array lengths must match (teamIds: ${teamIds.length}, groupTypeIndexes: ${groupTypeIndexes.length}, groupKeys: ${groupKeys.length})`
- )
- }
-
- if (teamIds.length === 0) {
+ if (keys.length === 0) {
return []
}
@@ -90,13 +83,17 @@ export class PostgresGroupRepository
const { rows } = await this.postgres.query(
tx ?? PostgresUse.PERSONS_READ,
- `SELECT g.team_id, g.group_type_index, g.group_key, g.group_properties
+ `SELECT g.team_id, g.group_type_index, g.group_key, g.group_properties, g.created_at, g.version
FROM posthog_group g
JOIN unnest($1::int[], $2::int[], $3::text[]) AS t(team_id, group_type_index, group_key)
ON g.team_id = t.team_id
AND g.group_type_index = t.group_type_index
AND g.group_key = t.group_key`,
- [teamIds, groupTypeIndexes, groupKeys],
+ [
+ keys.map(({ teamId }) => teamId),
+ keys.map(({ groupTypeIndex }) => groupTypeIndex),
+ keys.map(({ groupKey }) => groupKey),
+ ],
queryTag('fetchGroupsByKeys', callerTag)
)
@@ -112,10 +109,70 @@ export class PostgresGroupRepository
group_type_index: row.group_type_index as GroupTypeIndex,
group_key: row.group_key,
group_properties: row.group_properties,
+ created_at: DateTime.fromISO(row.created_at).toUTC(),
+ version: Number(row.version || 0),
}
})
}
+ async updateGroupsBatch(updates: GroupPropertiesToSetUpdate[]): Promise<Group[]> {
+ if (updates.length === 0) {
+ return []
+ }
+
+ // Sort by row identity so concurrent flushes lock overlapping rows in
+ // the same order. Postgres doesn't guarantee lock order for
+ // UPDATE ... FROM, but with small batches it nested-loops over the
+ // UNNEST in input order, so this removes the practical deadlock risk
+ // between pods; the residue degrades to the individual-write fallback.
+ const sortedUpdates = [...updates].sort(
+ (a, b) => a.teamId - b.teamId || a.groupTypeIndex - b.groupTypeIndex || a.groupKey.localeCompare(b.groupKey)
+ )
+
+ const teamIds: number[] = []
+ const groupTypeIndexes: number[] = []
+ const groupKeys: string[] = []
+ const propertiesToSet: string[] = []
+ const createdAts: string[] = []
+
+ for (const update of sortedUpdates) {
+ teamIds.push(update.teamId)
+ groupTypeIndexes.push(update.groupTypeIndex)
+ groupKeys.push(update.groupKey)
+ propertiesToSet.push(sanitizeJsonbValue(update.propertiesToSet))
+ createdAts.push(update.createdAt.toISO()!)
+ }
+
+ // Merge semantics (jsonb ||) applied server-side: concurrent writers
+ // can only race on the same key, never clobber each other's other
+ // keys, so no version assertion (and no conflict retry) is needed.
+ // UNNEST keeps the statement shape constant for prepared-statement reuse.
+ const { rows } = await this.postgres.query<RawGroup>(
+ PostgresUse.PERSONS_WRITE,
+ `
+ UPDATE posthog_group AS g SET
+ group_properties = COALESCE(g.group_properties, '{}'::jsonb) || batch.new_properties::jsonb,
+ created_at = LEAST(g.created_at, batch.new_created_at::timestamp with time zone),
+ version = COALESCE(g.version, 0)::numeric + 1
+ FROM UNNEST(
+ $1::int[],
+ $2::int[],
+ $3::text[],
+ $4::text[],
+ $5::text[]
+ ) AS batch(batch_team_id, batch_group_type_index, batch_group_key, new_properties, new_created_at)
+ WHERE g.team_id = batch.batch_team_id
+ AND g.group_type_index = batch.batch_group_type_index
+ AND g.group_key = batch.batch_group_key
+ RETURNING g.*
+ `,
+ [teamIds, groupTypeIndexes, groupKeys, propertiesToSet, createdAts],
+ 'updateGroupsBatch'
+ )
+
+ return rows.map((row) => this.toGroup(row))
+ }
+
async insertGroup(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
diff --git a/nodejs/src/common/groups/repositories/raw-postgres-group-repository.interface.ts b/nodejs/src/common/groups/repositories/raw-postgres-group-repository.interface.ts
index 6d98947eb220..58b6343c6a60 100644
--- a/nodejs/src/common/groups/repositories/raw-postgres-group-repository.interface.ts
+++ b/nodejs/src/common/groups/repositories/raw-postgres-group-repository.interface.ts
@@ -4,6 +4,8 @@ import { TransactionClient } from '~/common/utils/db/postgres'
import { Properties } from '~/plugin-scaffold'
import { Group, GroupTypeIndex, ProjectId, PropertiesLastOperation, PropertiesLastUpdatedAt, TeamId } from '~/types'
+import { GroupKey } from './group-repository.interface'
+
export interface RawPostgresGroupRepository {
fetchGroup(
teamId: TeamId,
@@ -14,9 +16,7 @@ export interface RawPostgresGroupRepository {
): Promise<Group | undefined>
fetchGroupsByKeys(
- teamIds: TeamId[],
- groupTypeIndexes: GroupTypeIndex[],
- groupKeys: string[],
+ keys: GroupKey[],
callerTag?: string,
tx?: TransactionClient
): Promise<
diff --git a/nodejs/src/common/personhog/client.test.ts b/nodejs/src/common/personhog/client.test.ts
index 0fbf65e0bd09..a1c1da6e64ef 100644
--- a/nodejs/src/common/personhog/client.test.ts
+++ b/nodejs/src/common/personhog/client.test.ts
@@ -356,8 +356,22 @@ describe('PersonHogClient', () => {
const result = await client.groups.fetchGroupsByKeys([1, 2], [0, 1], ['acme', 'globex'])
expect(result).toEqual([
- { team_id: 1, group_type_index: 0, group_key: 'acme', group_properties: { name: 'Acme' } },
- { team_id: 2, group_type_index: 1, group_key: 'globex', group_properties: { name: 'Globex' } },
+ {
+ team_id: 1,
+ group_type_index: 0,
+ group_key: 'acme',
+ group_properties: { name: 'Acme' },
+ created_at: DateTime.fromMillis(Number(CREATED_AT_MS), { zone: 'utc' }),
+ version: 3,
+ },
+ {
+ team_id: 2,
+ group_type_index: 1,
+ group_key: 'globex',
+ group_properties: { name: 'Globex' },
+ created_at: DateTime.fromMillis(Number(CREATED_AT_MS), { zone: 'utc' }),
+ version: 3,
+ },
])
})
@@ -380,7 +394,14 @@ describe('PersonHogClient', () => {
const result = await client.groups.fetchGroupsByKeys([1, 1], [0, 1], ['found', 'missing'])
expect(result).toEqual([
- { team_id: 1, group_type_index: 0, group_key: 'found', group_properties: { x: 1 } },
+ {
+ team_id: 1,
+ group_type_index: 0,
+ group_key: 'found',
+ group_properties: { x: 1 },
+ created_at: DateTime.fromMillis(Number(CREATED_AT_MS), { zone: 'utc' }),
+ version: 3,
+ },
])
})
diff --git a/nodejs/src/common/personhog/groups.ts b/nodejs/src/common/personhog/groups.ts
index 267c1eb86257..7b9630a9cedd 100644
--- a/nodejs/src/common/personhog/groups.ts
+++ b/nodejs/src/common/personhog/groups.ts
@@ -1,5 +1,6 @@
import { create } from '@bufbuild/protobuf'
import { Client } from '@connectrpc/connect'
+import { DateTime } from 'luxon'
import { PersonHogService } from '~/common/generated/personhog/personhog/service/v1/service_pb'
import { GroupKeySchema } from '~/common/generated/personhog/personhog/types/v1/common_pb'
@@ -70,6 +71,8 @@ export class PersonHogGroupOperations {
group_type_index: GroupTypeIndex
group_key: string
group_properties: Record<string, any>
+ created_at: DateTime
+ version: number
}[]
> {
if (teamIds.length === 0) {
@@ -81,6 +84,8 @@ export class PersonHogGroupOperations {
group_type_index: GroupTypeIndex
group_key: string
group_properties: Record<string, any>
+ created_at: DateTime
+ version: number
}[] = []
for (let i = 0; i < teamIds.length; i += PERSONHOG_BATCH_SIZE) {
@@ -109,6 +114,8 @@ export class PersonHogGroupOperations {
group_type_index: toGroupTypeIndex(result.key.groupTypeIndex),
group_key: result.key.groupKey,
group_properties: parseJsonBytes(result.group.groupProperties) ?? {},
+ created_at: epochMsToDateTime(result.group.createdAt),
+ version: Number(result.group.version),
})
}
}
diff --git a/nodejs/src/common/personhog/personhog-group-read-repository.test.ts b/nodejs/src/common/personhog/personhog-group-read-repository.test.ts
index bac515290972..d7313aa02387 100644
--- a/nodejs/src/common/personhog/personhog-group-read-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-group-read-repository.test.ts
@@ -1,4 +1,5 @@
import { Code, ConnectError, createRouterTransport } from '@connectrpc/connect'
+import { DateTime } from 'luxon'
import { PersonHogService } from '~/common/generated/personhog/personhog/service/v1/service_pb'
import { TeamId } from '~/types'
@@ -70,6 +71,8 @@ describe('PersonHogGroupReadRepository', () => {
group_type_index: 0,
group_key: 'company-1',
group_properties: { name: 'Acme Inc' },
+ created_at: DateTime.fromMillis(1704067200000, { zone: 'utc' }),
+ version: 1,
})
})
diff --git a/nodejs/src/common/personhog/personhog-group-repository.test.ts b/nodejs/src/common/personhog/personhog-group-repository.test.ts
index e2fbb467f268..ecaea43f382a 100644
--- a/nodejs/src/common/personhog/personhog-group-repository.test.ts
+++ b/nodejs/src/common/personhog/personhog-group-repository.test.ts
@@ -98,6 +98,7 @@ function createMockPostgres(): jest.Mocked<GroupRepository> {
fetchGroupTypesByTeamIds: jest.fn(),
fetchGroupTypesByProjectIds: jest.fn(),
insertGroup: jest.fn(),
+ updateGroupsBatch: jest.fn(),
updateGroup: jest.fn(),
updateGroupOptimistically: jest.fn(),
insertGroupType: jest.fn(),
@@ -212,6 +213,8 @@ describe('PersonHogGroupRepository', () => {
group_type_index: GROUP_TYPE_INDEX,
group_key: GROUP_KEY,
group_properties: { name: 'Acme Corp' },
+ created_at: CREATED_AT,
+ version: 1,
},
]
@@ -227,7 +230,9 @@ describe('PersonHogGroupRepository', () => {
})
const repo = createRepo(rolloutPercentage)
- const result = await repo.fetchGroupsByKeys([TEAM_ID], [GROUP_TYPE_INDEX], [GROUP_KEY])
+ const result = await repo.fetchGroupsByKeys([
+ { teamId: TEAM_ID, groupTypeIndex: GROUP_TYPE_INDEX, groupKey: GROUP_KEY },
+ ])
expect(result).toEqual(expectedResult)
if (expectGrpc) {
@@ -235,9 +240,7 @@ describe('PersonHogGroupRepository', () => {
expect(mockPostgres.fetchGroupsByKeys).not.toHaveBeenCalled()
} else {
expect(mockPostgres.fetchGroupsByKeys).toHaveBeenCalledWith(
- [TEAM_ID],
- [GROUP_TYPE_INDEX],
- [GROUP_KEY],
+ [{ teamId: TEAM_ID, groupTypeIndex: GROUP_TYPE_INDEX, groupKey: GROUP_KEY }],
undefined
)
expect(handlers.getGroupsBatch).not.toHaveBeenCalled()
@@ -248,7 +251,7 @@ describe('PersonHogGroupRepository', () => {
mockPostgres.fetchGroupsByKeys.mockResolvedValue([])
const repo = createRepo(rolloutPercentage)
- const result = await repo.fetchGroupsByKeys([], [], [])
+ const result = await repo.fetchGroupsByKeys([])
expect(result).toEqual([])
})
@@ -353,6 +356,8 @@ describe('PersonHogGroupRepository', () => {
group_type_index: GROUP_TYPE_INDEX,
group_key: GROUP_KEY,
group_properties: { name: 'Acme Corp' },
+ created_at: CREATED_AT,
+ version: 1,
},
]
handlers.getGroupsBatch.mockReturnValue({
@@ -365,7 +370,9 @@ describe('PersonHogGroupRepository', () => {
})
const repo = createRepo(0, new Set([TEAM_ID]))
- const result = await repo.fetchGroupsByKeys([TEAM_ID], [GROUP_TYPE_INDEX], [GROUP_KEY])
+ const result = await repo.fetchGroupsByKeys([
+ { teamId: TEAM_ID, groupTypeIndex: GROUP_TYPE_INDEX, groupKey: GROUP_KEY },
+ ])
expect(result).toEqual(expectedResult)
expect(handlers.getGroupsBatch).toHaveBeenCalled()
@@ -420,6 +427,8 @@ describe('PersonHogGroupRepository', () => {
group_type_index: GROUP_TYPE_INDEX,
group_key: GROUP_KEY,
group_properties: {},
+ created_at: CREATED_AT,
+ version: 1,
},
]
h.getGroupsBatch.mockImplementation(() => {
@@ -428,7 +437,9 @@ describe('PersonHogGroupRepository', () => {
pg.fetchGroupsByKeys.mockResolvedValue(expected)
return {
call: (repo: PersonHogGroupRepository) =>
- repo.fetchGroupsByKeys([TEAM_ID], [GROUP_TYPE_INDEX], [GROUP_KEY]),
+ repo.fetchGroupsByKeys([
+ { teamId: TEAM_ID, groupTypeIndex: GROUP_TYPE_INDEX, groupKey: GROUP_KEY },
+ ]),
expected,
}
},
diff --git a/nodejs/src/common/personhog/personhog-group-repository.ts b/nodejs/src/common/personhog/personhog-group-repository.ts
index b87596ac10ad..0eee6234de80 100644
--- a/nodejs/src/common/personhog/personhog-group-repository.ts
+++ b/nodejs/src/common/personhog/personhog-group-repository.ts
@@ -1,7 +1,11 @@
import { DateTime } from 'luxon'
import { GroupRepositoryTransaction } from '~/common/groups/repositories/group-repository-transaction.interface'
-import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'
+import {
+ GroupKey,
+ GroupPropertiesToSetUpdate,
+ GroupRepository,
+} from '~/common/groups/repositories/group-repository.interface'
import { logger } from '~/common/utils/logger'
import { Properties } from '~/plugin-scaffold'
import { Group, GroupTypeIndex, ProjectId, PropertiesLastOperation, PropertiesLastUpdatedAt, TeamId } from '~/types'
@@ -53,9 +57,7 @@ export class PersonHogGroupRepository implements GroupRepository {
}
async fetchGroupsByKeys(
- teamIds: TeamId[],
- groupTypeIndexes: GroupTypeIndex[],
- groupKeys: string[],
+ keys: GroupKey[],
callerTag?: string
): Promise<
{
@@ -63,25 +65,33 @@ export class PersonHogGroupRepository implements GroupRepository {
group_type_index: GroupTypeIndex
group_key: string
group_properties: Record<string, any>
+ created_at: DateTime
+ version: number
}[]
> {
+ const teamIds = keys.map(({ teamId }) => teamId)
if (!shouldUseGrpcForTeams(this.rolloutTeamIds, teamIds, this.grpcPercentage)) {
return timedPostgres(this.clientLabel, 'fetchGroupsByKeys', () =>
- this.postgres.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, callerTag)
+ this.postgres.fetchGroupsByKeys(keys, callerTag)
)
}
try {
return await timedGrpc(this.clientLabel, 'fetchGroupsByKeys', () =>
- this.grpcClient.groups.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, callerTag)
+ this.grpcClient.groups.fetchGroupsByKeys(
+ teamIds,
+ keys.map(({ groupTypeIndex }) => groupTypeIndex),
+ keys.map(({ groupKey }) => groupKey),
+ callerTag
+ )
)
} catch (error) {
logger.warn('[PersonHog] gRPC fetchGroupsByKeys failed, falling back to Postgres', {
- count: teamIds.length,
+ count: keys.length,
error: String(error),
})
return timedPostgres(this.clientLabel, 'fetchGroupsByKeys', () =>
- this.postgres.fetchGroupsByKeys(teamIds, groupTypeIndexes, groupKeys, callerTag)
+ this.postgres.fetchGroupsByKeys(keys, callerTag)
)
}
}
@@ -180,6 +190,10 @@ export class PersonHogGroupRepository implements GroupRepository {
)
}
+ updateGroupsBatch(updates: GroupPropertiesToSetUpdate[]): Promise<Group[]> {
+ return this.postgres.updateGroupsBatch(updates)
+ }
+
updateGroupOptimistically(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
diff --git a/nodejs/src/common/personhog/personhog-postgres-parity.test.ts b/nodejs/src/common/personhog/personhog-postgres-parity.test.ts
index c3ea339cfa43..722bba64a5d4 100644
--- a/nodejs/src/common/personhog/personhog-postgres-parity.test.ts
+++ b/nodejs/src/common/personhog/personhog-postgres-parity.test.ts
@@ -295,11 +295,10 @@ describe('PersonHog ↔ Postgres parity', () => {
{}
)
- const fromPostgres = await postgresRepo.fetchGroupsByKeys(
- [teamId, teamId],
- [0 as GroupTypeIndex, 1 as GroupTypeIndex],
- ['acme', 'eng-team']
- )
+ const fromPostgres = await postgresRepo.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'acme' },
+ { teamId, groupTypeIndex: 1 as GroupTypeIndex, groupKey: 'eng-team' },
+ ])
const rawAcme = await readRawGroup(teamId, 0, 'acme')
const rawEng = await readRawGroup(teamId, 1, 'eng-team')
@@ -338,11 +337,10 @@ describe('PersonHog ↔ Postgres parity', () => {
{}
)
- const fromPostgres = await postgresRepo.fetchGroupsByKeys(
- [teamId, teamId],
- [0 as GroupTypeIndex, 0 as GroupTypeIndex],
- ['exists', 'missing']
- )
+ const fromPostgres = await postgresRepo.fetchGroupsByKeys([
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'exists' },
+ { teamId, groupTypeIndex: 0 as GroupTypeIndex, groupKey: 'missing' },
+ ])
const rawExists = await readRawGroup(teamId, 0, 'exists')
@@ -370,7 +368,7 @@ describe('PersonHog ↔ Postgres parity', () => {
})
it('empty input produces identical output', async () => {
- const fromPostgres = await postgresRepo.fetchGroupsByKeys([], [], [])
+ const fromPostgres = await postgresRepo.fetchGroupsByKeys([])
const grpcClient = createMockPersonHogClient({})
const fromGrpc = await grpcClient.groups.fetchGroupsByKeys([], [], [])
diff --git a/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts b/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts
index 70cc93e26cec..0dd9cf6fa310 100644
--- a/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts
+++ b/nodejs/src/ingestion/common/groups/batch-writing-group-store.test.ts
@@ -1,8 +1,8 @@
// sort-imports-ignore
import { DateTime } from 'luxon'
-import { Group, ProjectId, TeamId } from '~/types'
-import { MessageSizeTooLarge } from '~/common/utils/db/error'
+import { Group, GroupTypeIndex, ProjectId, TeamId } from '~/types'
+import { parseJSON } from '~/common/utils/json-parse'
import { RaceConditionError } from '~/common/utils/utils'
import { BatchWritingGroupStore } from './batch-writing-group-store'
@@ -10,13 +10,7 @@ import { groupCacheOperationsCounter } from './metrics'
import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhouse-group-repository'
import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'
-// Mock the module before importing
-jest.mock('~/ingestion/common/ingestion-warnings', () => ({
- emitIngestionWarning: jest.fn().mockResolvedValue(undefined),
-}))
-
-import { GroupsOutput, IngestionWarningsOutput } from '~/common/outputs'
-import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
+import { GroupsOutput } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
// Mock the DB class
@@ -25,10 +19,10 @@ describe('BatchWritingGroupStore', () => {
let groupRepository: GroupRepository
let groupStore: BatchWritingGroupStore
let clickhouseGroupRepository: ClickhouseGroupRepository
+ let mockQueueMessages: jest.Mock
let teamId: TeamId
let projectId: ProjectId
let group: Group
- let mockOutputs: IngestionOutputs<GroupsOutput | IngestionWarningsOutput>
beforeEach(() => {
teamId = 1
@@ -53,6 +47,8 @@ describe('BatchWritingGroupStore', () => {
fetchGroup: jest.fn().mockImplementation(() => {
return Promise.resolve(group)
}),
+ fetchGroupsByKeys: jest.fn().mockResolvedValue([]),
+ updateGroupsBatch: jest.fn().mockResolvedValue([]),
insertGroup: jest.fn().mockImplementation(() => {
return Promise.resolve(1)
}),
@@ -104,11 +100,13 @@ describe('BatchWritingGroupStore', () => {
// Reset the counter before each test
groupCacheOperationsCounter.reset()
- clickhouseGroupRepository = {
- upsertGroup: jest.fn().mockResolvedValue(undefined),
- } as unknown as ClickhouseGroupRepository
- mockOutputs = {} as unknown as IngestionOutputs<GroupsOutput | IngestionWarningsOutput>
- groupStore = new BatchWritingGroupStore(mockOutputs, groupRepository, clickhouseGroupRepository)
+ // Real repository over a mocked producer: buildUpsertMessage is pure,
+ // and only the inline create/fallback paths call queueMessages.
+ mockQueueMessages = jest.fn().mockResolvedValue(undefined)
+ clickhouseGroupRepository = new ClickhouseGroupRepository({
+ queueMessages: mockQueueMessages,
+ } as unknown as IngestionOutputs<GroupsOutput>)
+ groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository)
})
afterEach(async () => {
@@ -134,7 +132,7 @@ describe('BatchWritingGroupStore', () => {
await groupStore.upsertGroup(teamId, projectId, 1, 'test', { b: 'test' }, DateTime.now())
await groupStore.upsertGroup(teamId, projectId, 1, 'test', { c: 'test' }, DateTime.now())
- await groupStore.flush()
+ const results = await groupStore.flush()
expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
@@ -152,6 +150,12 @@ describe('BatchWritingGroupStore', () => {
{}
)
+ // The ClickHouse message is returned for side-effect production, not produced inline.
+ expect(results).toHaveLength(1)
+ expect(results[0]).toMatchObject({ teamId, groupTypeIndex: 1, groupKey: 'test' })
+ expect(results[0].messages).toHaveLength(1)
+ expect(mockQueueMessages).not.toHaveBeenCalled()
+
const cacheMetrics = groupStore.getCacheMetrics()
expect(cacheMetrics.cacheHits).toBe(2)
@@ -165,8 +169,17 @@ describe('BatchWritingGroupStore', () => {
expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)
expect(groupRepository.updateGroup).toHaveBeenCalledTimes(0)
- expect(groupRepository.inTransaction).toHaveBeenCalledTimes(1)
- expect((groupRepository as any).lastTransactionMock.insertGroup).toHaveBeenCalledTimes(1)
+ // Creation is a single ON CONFLICT insert — no wrapping transaction.
+ expect(groupRepository.inTransaction).toHaveBeenCalledTimes(0)
+ expect(groupRepository.insertGroup).toHaveBeenCalledTimes(1)
+ // The ClickHouse message is NOT awaited inline (delivery reports on a
+ // backpressured producer stall the sequential per-distinct-id lane);
+ // it rides the next flush's side effects instead.
+ expect(mockQueueMessages).not.toHaveBeenCalled()
+
+ const results = await groupStore.flush()
+ expect(results).toHaveLength(1)
+ expect(results[0]).toMatchObject({ teamId, groupTypeIndex: 1, groupKey: 'test' })
})
it('should accumulate changes in cache after db write, even if new group', async () => {
@@ -181,8 +194,8 @@ describe('BatchWritingGroupStore', () => {
expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(1)
expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
expect(groupRepository.updateGroup).toHaveBeenCalledTimes(0)
- expect(groupRepository.inTransaction).toHaveBeenCalledTimes(1)
- expect((groupRepository as any).lastTransactionMock.insertGroup).toHaveBeenCalledTimes(1)
+ expect(groupRepository.inTransaction).toHaveBeenCalledTimes(0)
+ expect(groupRepository.insertGroup).toHaveBeenCalledTimes(1)
expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledWith(
teamId,
@@ -248,19 +261,24 @@ describe('BatchWritingGroupStore', () => {
it('should fall back to direct upsert if optimistic update fails', async () => {
jest.spyOn(groupRepository, 'updateGroupOptimistically').mockResolvedValue(undefined)
jest.spyOn(groupRepository, 'updateGroup').mockResolvedValue(2)
+ // Conflict refetches return a group WITHOUT our properties, so the
+ // short-circuit doesn't kick in and every attempt retries.
jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValue(group)
await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: 'updated' }, DateTime.now())
expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)
expect(groupRepository.updateGroup).toHaveBeenCalledTimes(0)
- expect(clickhouseGroupRepository.upsertGroup).toHaveBeenCalledTimes(0)
+ expect(mockQueueMessages).toHaveBeenCalledTimes(0)
- await groupStore.flush()
+ const results = await groupStore.flush()
expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(5)
expect(groupRepository.inTransaction).toHaveBeenCalledTimes(1)
expect((groupRepository as any).lastTransactionMock.updateGroup).toHaveBeenCalledTimes(1)
- expect(clickhouseGroupRepository.upsertGroup).toHaveBeenCalledTimes(1)
+ // The fallback path's ClickHouse message rides this flush's results
+ // instead of being produced inline.
+ expect(mockQueueMessages).not.toHaveBeenCalled()
+ expect(results).toHaveLength(1)
})
it('should share cache between distinct ids', async () => {
@@ -283,47 +301,58 @@ describe('BatchWritingGroupStore', () => {
)
})
- it('should not write to db if no properties are changed', async () => {
- // Mock the groupRepository.fetchGroup to return a group with the same properties
- jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValue(group)
+ it('keeps separate cache entries for two group types sharing a group key', async () => {
+ // A cache key without group_type_index would make the second upsert
+ // read the first type's cached row, merge both types' properties into
+ // one entry, and flush a single contaminated write.
+ jest.spyOn(groupRepository, 'fetchGroup').mockImplementation((_teamId, groupTypeIndex) =>
+ Promise.resolve({ ...group, group_type_index: groupTypeIndex, group_properties: {} })
+ )
- await groupStore.upsertGroup(teamId, projectId, 1, 'test', group.group_properties, DateTime.now())
+ await groupStore.upsertGroup(teamId, projectId, 0, 'shared-key', { a: '1' }, DateTime.now())
+ await groupStore.upsertGroup(teamId, projectId, 1, 'shared-key', { b: '2' }, DateTime.now())
await groupStore.flush()
- expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)
- expect(groupRepository.updateGroup).toHaveBeenCalledTimes(0)
- expect(groupRepository.inTransaction).toHaveBeenCalledTimes(0)
- // No transaction calls expected since no properties changed
+ expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(2)
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(2)
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledWith(
+ teamId,
+ 0,
+ 'shared-key',
+ 1,
+ { a: '1' },
+ group.created_at,
+ {},
+ {}
+ )
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledWith(
+ teamId,
+ 1,
+ 'shared-key',
+ 1,
+ { b: '2' },
+ group.created_at,
+ {},
+ {}
+ )
})
- it('should capture warning and stop retrying if message size too large', async () => {
- // we need to mock the clickhouse repository upsertGroup method
- clickhouseGroupRepository.upsertGroup = jest
- .fn()
- .mockRejectedValue(new MessageSizeTooLarge('test', new Error('test')))
+ it('should not write to db if no properties are changed', async () => {
+ // Mock the groupRepository.fetchGroup to return a group with the same properties
+ jest.spyOn(groupRepository, 'fetchGroup').mockResolvedValue(group)
- await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: 'test' }, DateTime.now())
+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', group.group_properties, DateTime.now())
await groupStore.flush()
- expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)
expect(groupRepository.updateGroup).toHaveBeenCalledTimes(0)
expect(groupRepository.inTransaction).toHaveBeenCalledTimes(0)
- // No transaction calls expected since optimistic update failed
- expect(emitIngestionWarning).toHaveBeenCalledWith(mockOutputs, teamId, {
- type: 'group_upsert_message_size_too_large',
- details: {
- groupTypeIndex: 1,
- groupKey: 'test',
- distinctId: `${teamId}:test`,
- },
- pipelineStep: 'group-store',
- })
+ // No transaction calls expected since no properties changed
})
it('should retry on race condition error and clear cache', async () => {
- let insertCounter = 0
let fetchCounter = 0
jest.spyOn(groupRepository, 'fetchGroup').mockImplementation(() => {
fetchCounter++
@@ -334,26 +363,10 @@ describe('BatchWritingGroupStore', () => {
}
})
- // Override the transaction mock to throw on first insertGroup call
- groupRepository.inTransaction = jest.fn().mockImplementation(async (description, transaction) => {
- const mockTransaction = {
- fetchGroup: jest.fn().mockImplementation(() => {
- return Promise.resolve(group)
- }),
- insertGroup: jest.fn().mockImplementation(() => {
- insertCounter++
- if (insertCounter === 1) {
- throw new RaceConditionError('Parallel posthog_group inserts, retry')
- }
- return Promise.resolve(1)
- }),
- updateGroup: jest.fn().mockImplementation(() => {
- return Promise.resolve(1)
- }),
- }
- ;(groupRepository as any).lastTransactionMock = mockTransaction
- return await transaction(mockTransaction)
- })
+ // The group was created by another pod between our fetch and insert.
+ jest.spyOn(groupRepository, 'insertGroup').mockRejectedValueOnce(
+ new RaceConditionError('Parallel posthog_group inserts, retry')
+ )
// track cache delete
const groupCache = groupStore.getGroupCache()
@@ -364,14 +377,12 @@ describe('BatchWritingGroupStore', () => {
await groupStore.flush()
- expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ expect(groupRepository.insertGroup).toHaveBeenCalledTimes(1)
expect(groupRepository.fetchGroup).toHaveBeenCalledTimes(2) // Once for initial fetch, once for retry
- expect(groupRepository.inTransaction).toHaveBeenCalledTimes(1) // Once for initial insert, once for retry (new group)
- expect((groupRepository as any).lastTransactionMock.insertGroup).toHaveBeenCalledTimes(1)
+ expect(cacheDeleteSpy).toHaveBeenCalledWith(teamId, 1, 'test')
- expect(cacheDeleteSpy).toHaveBeenCalledWith(teamId, 'test')
-
- // Final call should succeed
+ // The retry found the winning row and flushed our properties onto it.
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
expect(groupRepository.updateGroupOptimistically).toHaveBeenLastCalledWith(
teamId,
1,
@@ -384,6 +395,168 @@ describe('BatchWritingGroupStore', () => {
)
})
+ it('should not write when object-valued properties are deeply equal', async () => {
+ // Object values arrive as fresh JSON parses each event; a reference
+ // compare here would dirty the group on every event and re-open the
+ // no-op write storm this store had in production.
+ group.group_properties = { nested: { plan: 'scale', seats: 5 } }
+
+ await groupStore.upsertGroup(
+ teamId,
+ projectId,
+ 1,
+ 'test',
+ { nested: { plan: 'scale', seats: 5 } },
+ DateTime.now()
+ )
+ const results = await groupStore.flush()
+
+ expect(results).toHaveLength(0)
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(0)
+ })
+
+ it('should skip the retry when a conflicting writer already persisted the same properties', async () => {
+ jest.spyOn(groupRepository, 'updateGroupOptimistically').mockResolvedValue(undefined)
+ jest.spyOn(groupRepository, 'fetchGroup')
+ .mockResolvedValueOnce(group)
+ .mockResolvedValue({ ...group, group_properties: { test: 'test', a: 'test' }, version: 7 })
+
+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: 'test' }, DateTime.now())
+ const results = await groupStore.flush()
+
+ // One failed CAS, then the refetch shows the winner already wrote our
+ // properties — no retries, no fallback, no ClickHouse message.
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ expect(groupRepository.inTransaction).toHaveBeenCalledTimes(0)
+ expect(results).toHaveLength(0)
+ expect(groupStore.getGroupCache().get(teamId, 1, 'test')?.version).toBe(7)
+ })
+
+ describe('useBatchUpdates', () => {
+ beforeEach(() => {
+ groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {
+ useBatchUpdates: true,
+ })
+ })
+
+ it('flushes all dirty groups in one statement, routing each merged row and fallback to its own group', async () => {
+ // Each group gets its own row back, distinct rows include keys the
+ // DB merged from other pods, and one group is missing from the
+ // result (deleted or never created) so it falls back to an
+ // individual write.
+ jest.spyOn(groupRepository, 'fetchGroup').mockImplementation((_teamId, groupTypeIndex, groupKey) =>
+ Promise.resolve({ ...group, group_type_index: groupTypeIndex, group_key: groupKey })
+ )
+ const rowA = {
+ ...group,
+ group_type_index: 0 as GroupTypeIndex,
+ group_key: 'g-a',
+ group_properties: { test: 'test', a: '1', from_other_pod: 'x' },
+ version: 5,
+ }
+ const rowB = {
+ ...group,
+ group_type_index: 1 as GroupTypeIndex,
+ group_key: 'g-b',
+ group_properties: { test: 'test', b: '2' },
+ version: 9,
+ }
+ jest.spyOn(groupRepository, 'updateGroupsBatch').mockResolvedValue([rowA, rowB])
+
+ await groupStore.upsertGroup(teamId, projectId, 0, 'g-a', { a: '1' }, DateTime.now())
+ await groupStore.upsertGroup(teamId, projectId, 1, 'g-b', { b: '2' }, DateTime.now())
+ await groupStore.upsertGroup(teamId, projectId, 0, 'g-missing', { c: '3' }, DateTime.now())
+
+ const results = await groupStore.flush()
+
+ expect(groupRepository.updateGroupsBatch).toHaveBeenCalledTimes(1)
+ expect(groupRepository.updateGroupsBatch).toHaveBeenCalledWith([
+ {
+ teamId,
+ groupTypeIndex: 0,
+ groupKey: 'g-a',
+ propertiesToSet: { a: '1' },
+ createdAt: group.created_at,
+ },
+ {
+ teamId,
+ groupTypeIndex: 1,
+ groupKey: 'g-b',
+ propertiesToSet: { b: '2' },
+ createdAt: group.created_at,
+ },
+ {
+ teamId,
+ groupTypeIndex: 0,
+ groupKey: 'g-missing',
+ propertiesToSet: { c: '3' },
+ createdAt: group.created_at,
+ },
+ ])
+
+ // Only the group missing from the batch result goes through the individual path.
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ expect(jest.mocked(groupRepository.updateGroupOptimistically).mock.calls[0][2]).toBe('g-missing')
+
+ // Each ClickHouse message reflects that group's own authoritative row.
+ expect(results).toHaveLength(3)
+ const messagesByKey = new Map(
+ results.map((result) => [result.groupKey, parseJSON(result.messages[0].value.toString())])
+ )
+ expect(parseJSON(messagesByKey.get('g-a').group_properties)).toEqual(rowA.group_properties)
+ expect(messagesByKey.get('g-a').version).toBe(5)
+ expect(messagesByKey.get('g-a').group_type_index).toBe(0)
+ expect(parseJSON(messagesByKey.get('g-b').group_properties)).toEqual(rowB.group_properties)
+ expect(messagesByKey.get('g-b').version).toBe(9)
+ expect(messagesByKey.get('g-b').group_type_index).toBe(1)
+
+ // The cache converges on each group's own merged row.
+ expect(groupStore.getGroupCache().get(teamId, 0, 'g-a')?.version).toBe(5)
+ expect(groupStore.getGroupCache().get(teamId, 0, 'g-a')?.group_properties).toEqual(rowA.group_properties)
+ expect(groupStore.getGroupCache().get(teamId, 1, 'g-b')?.version).toBe(9)
+ expect(groupStore.getGroupCache().get(teamId, 1, 'g-b')?.group_properties).toEqual(rowB.group_properties)
+ })
+
+ it('falls back to individual writes when the batch statement fails', async () => {
+ jest.spyOn(groupRepository, 'updateGroupsBatch').mockRejectedValue(new Error('connection lost'))
+
+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now())
+ const results = await groupStore.flush()
+
+ expect(groupRepository.updateGroupOptimistically).toHaveBeenCalledTimes(1)
+ expect(results).toHaveLength(1)
+ })
+ })
+
+ describe('prefetchGroups', () => {
+ it('serves subsequent upserts from the prefetched cache without single-row fetches', async () => {
+ jest.spyOn(groupRepository, 'fetchGroupsByKeys').mockResolvedValue([
+ {
+ team_id: teamId,
+ group_type_index: 1,
+ group_key: 'test',
+ group_properties: { test: 'test' },
+ created_at: group.created_at,
+ version: 1,
+ },
+ ])
+
+ await groupStore.prefetchGroups([
+ { teamId, groupTypeIndex: 1, groupKey: 'test', batchId: 0 },
+ { teamId, groupTypeIndex: 1, groupKey: 'missing', batchId: 0 },
+ ])
+
+ await groupStore.upsertGroup(teamId, projectId, 1, 'test', { a: '1' }, DateTime.now(), 0)
+ // The missing key was negative-cached, so the create path goes
+ // straight to insert without another read.
+ await groupStore.upsertGroup(teamId, projectId, 1, 'missing', { b: '2' }, DateTime.now(), 0)
+
+ expect(groupRepository.fetchGroupsByKeys).toHaveBeenCalledTimes(1)
+ expect(groupRepository.fetchGroup).not.toHaveBeenCalled()
+ expect(groupRepository.insertGroup).toHaveBeenCalledTimes(1)
+ })
+ })
+
describe('persistent cache (concurrentBatches > 1)', () => {
it('clears needsWrite on dirty entries synchronously during flush', async () => {
// Linearization point: flush() must clear needsWrite BEFORE awaiting
@@ -470,7 +643,7 @@ describe('BatchWritingGroupStore', () => {
// Re-dirty the entry during the async DB write after the linearization point.
jest.spyOn(groupRepository, 'updateGroupOptimistically').mockImplementationOnce(() => {
- const entry = groupStore.getGroupCache().get(teamId, 'test')
+ const entry = groupStore.getGroupCache().get(teamId, 1, 'test')
if (entry) {
entry.needsWrite = true
}
@@ -480,7 +653,7 @@ describe('BatchWritingGroupStore', () => {
await groupStore.flush()
expect(groupStore.getGroupCache().getSize()).toBe(1)
- expect(groupStore.getGroupCache().get(teamId, 'test')?.needsWrite).toBe(true)
+ expect(groupStore.getGroupCache().get(teamId, 1, 'test')?.needsWrite).toBe(true)
})
it('defers eviction of dirty entries until after flush', async () => {
diff --git a/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts b/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts
index 3d0d23b3dd49..51f72af4180c 100644
--- a/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts
+++ b/nodejs/src/ingestion/common/groups/batch-writing-group-store.ts
@@ -1,23 +1,21 @@
import { DateTime } from 'luxon'
import pLimit from 'p-limit'
-import { ClickhouseGroupRepository } from '~/common/groups/repositories/clickhouse-group-repository'
+import {
+ ClickhouseGroupRepository,
+ GroupClickhouseMessage,
+} from '~/common/groups/repositories/clickhouse-group-repository'
import { GroupRepositoryTransaction } from '~/common/groups/repositories/group-repository-transaction.interface'
import { GroupRepository } from '~/common/groups/repositories/group-repository.interface'
-import { GroupsOutput, IngestionWarningsOutput } from '~/common/outputs'
-import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
-import { MessageSizeTooLarge } from '~/common/utils/db/error'
import { logger } from '~/common/utils/logger'
import { promiseRetry } from '~/common/utils/retries'
import { RaceConditionError } from '~/common/utils/utils'
-import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
-import { FlushResult } from '~/ingestion/common/persons/persons-store'
import { BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
import { Properties } from '~/plugin-scaffold'
-import { GroupTypeIndex, TeamId } from '~/types'
+import { Group, GroupTypeIndex, TeamId } from '~/types'
import { logMissingRow, logVersionMismatch } from './group-logging'
-import { CacheMetrics, GroupStore } from './group-store.interface'
+import { CacheMetrics, GroupFlushResult, GroupStore } from './group-store.interface'
import { GroupUpdate, calculateUpdate, fromGroup } from './group-update'
import {
groupCacheOperationsCounter,
@@ -34,6 +32,8 @@ class GroupCache {
private batchGroupKeys: Map<number, Set<string>>
private groupKeyRefCount: Map<string, number>
private deferredEvictions: Set<string>
+ private pendingPrefetchesByBatchId: Map<number, number>
+ private releasedBatchIdsWithPendingPrefetch: Set<number>
constructor() {
this.cache = new Map()
@@ -41,6 +41,8 @@ class GroupCache {
this.batchGroupKeys = new Map()
this.groupKeyRefCount = new Map()
this.deferredEvictions = new Set()
+ this.pendingPrefetchesByBatchId = new Map()
+ this.releasedBatchIdsWithPendingPrefetch = new Set()
this.metrics = {
cacheHits: 0,
cacheMisses: 0,
@@ -51,19 +53,24 @@ class GroupCache {
return new BatchBoundGroupCache(this, batchId)
}
- get(teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {
- return this.cache.get(this.getCacheKey(teamId, groupKey))
+ get(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): GroupUpdate | null | undefined {
+ return this.cache.get(this.getCacheKey(teamId, groupTypeIndex, groupKey))
}
- hasForBatch(batchId: number, teamId: TeamId, groupKey: string): boolean {
- this.trackBatchEntry(batchId, teamId, groupKey)
- const key = this.getCacheKey(teamId, groupKey)
+ hasForBatch(batchId: number, teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): boolean {
+ this.trackBatchEntry(batchId, teamId, groupTypeIndex, groupKey)
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
return this.cache.has(key)
}
- getForBatch(batchId: number, teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {
- this.trackBatchEntry(batchId, teamId, groupKey)
- const key = this.getCacheKey(teamId, groupKey)
+ getForBatch(
+ batchId: number,
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string
+ ): GroupUpdate | null | undefined {
+ this.trackBatchEntry(batchId, teamId, groupTypeIndex, groupKey)
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
const result = this.cache.get(key)
if (result !== undefined) {
this.metrics.cacheHits++
@@ -73,29 +80,44 @@ class GroupCache {
return result
}
- setForBatch(batchId: number, teamId: TeamId, groupKey: string, group: GroupUpdate | null): void {
- this.trackBatchEntry(batchId, teamId, groupKey)
- const key = this.getCacheKey(teamId, groupKey)
+ setForBatch(
+ batchId: number,
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string,
+ group: GroupUpdate | null
+ ): void {
+ this.trackBatchEntry(batchId, teamId, groupTypeIndex, groupKey)
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
this.cache.set(key, group)
}
- delete(teamId: TeamId, groupKey: string): void {
- const key = this.getCacheKey(teamId, groupKey)
+ delete(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): void {
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
this.cache.delete(key)
}
- getFetchPromise(teamId: TeamId, groupKey: string): Promise<GroupUpdate | null> | undefined {
- const key = this.getCacheKey(teamId, groupKey)
+ getFetchPromise(
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string
+ ): Promise<GroupUpdate | null> | undefined {
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
return this.fetchPromises.get(key)
}
- setFetchPromise(teamId: TeamId, groupKey: string, promise: Promise<GroupUpdate | null>): void {
- const key = this.getCacheKey(teamId, groupKey)
+ setFetchPromise(
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string,
+ promise: Promise<GroupUpdate | null>
+ ): void {
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
this.fetchPromises.set(key, promise)
}
- deleteFetchPromise(teamId: TeamId, groupKey: string): void {
- const key = this.getCacheKey(teamId, groupKey)
+ deleteFetchPromise(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): void {
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
this.fetchPromises.delete(key)
}
@@ -149,6 +171,9 @@ class GroupCache {
releaseBatchId(batchId: number): void {
const keys = this.batchGroupKeys.get(batchId)
+ if (this.pendingPrefetchesByBatchId.has(batchId)) {
+ this.releasedBatchIdsWithPendingPrefetch.add(batchId)
+ }
if (!keys) {
return
}
@@ -166,6 +191,28 @@ class GroupCache {
this.batchGroupKeys.delete(batchId)
}
+ trackPendingPrefetch(batchIds: Set<number>): void {
+ for (const batchId of batchIds) {
+ this.pendingPrefetchesByBatchId.set(batchId, (this.pendingPrefetchesByBatchId.get(batchId) ?? 0) + 1)
+ }
+ }
+
+ finishPendingPrefetch(batchIds: Set<number>): void {
+ for (const batchId of batchIds) {
+ const pendingCount = (this.pendingPrefetchesByBatchId.get(batchId) ?? 1) - 1
+ if (pendingCount <= 0) {
+ this.pendingPrefetchesByBatchId.delete(batchId)
+ this.releasedBatchIdsWithPendingPrefetch.delete(batchId)
+ } else {
+ this.pendingPrefetchesByBatchId.set(batchId, pendingCount)
+ }
+ }
+ }
+
+ isBatchReleasedWithPendingPrefetch(batchId: number): boolean {
+ return this.releasedBatchIdsWithPendingPrefetch.has(batchId)
+ }
+
processDeferredEvictions(): void {
for (const groupKey of this.deferredEvictions) {
const update = this.cache.get(groupKey)
@@ -176,12 +223,15 @@ class GroupCache {
}
}
- private getCacheKey(teamId: TeamId, groupKey: string): string {
- return `${teamId}:${groupKey}`
+ // The key must carry group_type_index: two group types can share a group
+ // key, and a key without the index would make them read and overwrite
+ // each other's cached row.
+ private getCacheKey(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): string {
+ return `${teamId}:${groupTypeIndex}:${groupKey}`
}
- private trackBatchEntry(batchId: number, teamId: TeamId, groupKey: string): void {
- const key = this.getCacheKey(teamId, groupKey)
+ private trackBatchEntry(batchId: number, teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): void {
+ const key = this.getCacheKey(teamId, groupTypeIndex, groupKey)
let keys = this.batchGroupKeys.get(batchId)
if (!keys) {
keys = new Set()
@@ -210,28 +260,37 @@ class BatchBoundGroupCache {
private readonly batchId: number
) {}
- has(teamId: TeamId, groupKey: string): boolean {
- return this.cache.hasForBatch(this.batchId, teamId, groupKey)
+ has(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): boolean {
+ return this.cache.hasForBatch(this.batchId, teamId, groupTypeIndex, groupKey)
}
- get(teamId: TeamId, groupKey: string): GroupUpdate | null | undefined {
- return this.cache.getForBatch(this.batchId, teamId, groupKey)
+ get(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): GroupUpdate | null | undefined {
+ return this.cache.getForBatch(this.batchId, teamId, groupTypeIndex, groupKey)
}
- set(teamId: TeamId, groupKey: string, group: GroupUpdate | null): void {
- this.cache.setForBatch(this.batchId, teamId, groupKey, group)
+ set(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string, group: GroupUpdate | null): void {
+ this.cache.setForBatch(this.batchId, teamId, groupTypeIndex, groupKey, group)
}
- getFetchPromise(teamId: TeamId, groupKey: string): Promise<GroupUpdate | null> | undefined {
- return this.cache.getFetchPromise(teamId, groupKey)
+ getFetchPromise(
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string
+ ): Promise<GroupUpdate | null> | undefined {
+ return this.cache.getFetchPromise(teamId, groupTypeIndex, groupKey)
}
- setFetchPromise(teamId: TeamId, groupKey: string, promise: Promise<GroupUpdate | null>): void {
- this.cache.setFetchPromise(teamId, groupKey, promise)
+ setFetchPromise(
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string,
+ promise: Promise<GroupUpdate | null>
+ ): void {
+ this.cache.setFetchPromise(teamId, groupTypeIndex, groupKey, promise)
}
- deleteFetchPromise(teamId: TeamId, groupKey: string): void {
- this.cache.deleteFetchPromise(teamId, groupKey)
+ deleteFetchPromise(teamId: TeamId, groupTypeIndex: GroupTypeIndex, groupKey: string): void {
+ this.cache.deleteFetchPromise(teamId, groupTypeIndex, groupKey)
}
}
@@ -244,6 +303,13 @@ export interface BatchWritingGroupStoreOptions {
maxConcurrentUpdates: number
maxOptimisticUpdateRetries: number
optimisticUpdateRetryInterval: number
+ /**
+ * When true, flush writes all dirty groups in a single UNNEST statement
+ * with server-side jsonb merge semantics (no version CAS, no conflict
+ * retries). When false, each group is written individually with an
+ * optimistic version check.
+ */
+ useBatchUpdates: boolean
/**
* Interval at which accumulated group operation metrics are emitted and
* cleared. Set to 0 to disable the timer (used by tests; production
@@ -256,9 +322,17 @@ const DEFAULT_OPTIONS: BatchWritingGroupStoreOptions = {
maxConcurrentUpdates: 10,
maxOptimisticUpdateRetries: 5,
optimisticUpdateRetryInterval: 50,
+ useBatchUpdates: false,
metricEmissionIntervalMs: 30_000,
}
+interface PendingGroupWrite {
+ update: GroupUpdate
+ /** Delta captured (and reset) at the flush linearization point. */
+ propertiesToSet: Properties
+ cacheKey: string
+}
+
/**
* Writes groups to the database in batches, accumulating all changes for the
* same group across events and flushing them on `flush()` calls. The cache
@@ -270,9 +344,10 @@ const DEFAULT_OPTIONS: BatchWritingGroupStoreOptions = {
*/
export class BatchWritingGroupStore implements GroupStore {
private groupCache: GroupCache
+ /** ClickHouse messages queued by create/fallback paths, drained by flush(). */
+ private pendingFlushResults: GroupFlushResult[] = []
private databaseOperationCounts: Map<string, number>
private options: BatchWritingGroupStoreOptions
- private outputs: IngestionOutputs<GroupsOutput | IngestionWarningsOutput>
private groupRepository: GroupRepository
private clickhouseGroupRepository: ClickhouseGroupRepository
// Periodic metric emitter — emits accumulated group-operation metrics on
@@ -280,7 +355,6 @@ export class BatchWritingGroupStore implements GroupStore {
private metricEmissionTimer: NodeJS.Timeout | undefined
constructor(
- outputs: IngestionOutputs<GroupsOutput | IngestionWarningsOutput>,
groupRepository: GroupRepository,
clickhouseGroupRepository: ClickhouseGroupRepository,
options?: Partial<BatchWritingGroupStoreOptions>
@@ -288,7 +362,6 @@ export class BatchWritingGroupStore implements GroupStore {
this.options = { ...DEFAULT_OPTIONS, ...options }
this.groupCache = new GroupCache()
this.databaseOperationCounts = new Map()
- this.outputs = outputs
this.groupRepository = groupRepository
this.clickhouseGroupRepository = clickhouseGroupRepository
@@ -305,14 +378,14 @@ export class BatchWritingGroupStore implements GroupStore {
return this.groupCache
}
- async flush(): Promise<FlushResult[]> {
+ async flush(): Promise<GroupFlushResult[]> {
// SYNCHRONOUS LINEARIZATION POINT for cross-batch correctness.
- // Walk every dirty entry, capture it for writing, and clear
- // `needsWrite` before any await below. Concurrent batches that
+ // Walk every dirty entry, capture it (and its delta) for writing, and
+ // clear `needsWrite` before any await below. Concurrent batches that
// mutate an entry between this clear and the async DB write will
// re-set `needsWrite=true` and be picked up by the next flush.
// DO NOT introduce any `await` inside this block.
- const pendingUpdates: [string, GroupUpdate][] = []
+ const pendingWrites: PendingGroupWrite[] = []
for (const [key, update] of this.groupCache.entries()) {
if (!update) {
continue
@@ -321,23 +394,25 @@ export class BatchWritingGroupStore implements GroupStore {
continue
}
update.needsWrite = false
- pendingUpdates.push([key, update])
+ const propertiesToSet = update.properties_to_set
+ update.properties_to_set = {}
+ pendingWrites.push({ update, propertiesToSet, cacheKey: key })
}
// END synchronous linearization point.
- if (pendingUpdates.length === 0) {
+ if (pendingWrites.length === 0) {
this.groupCache.processDeferredEvictions()
- return []
+ return this.drainPendingFlushResults()
}
- const limit = pLimit(this.options.maxConcurrentUpdates)
-
try {
- await Promise.all(
- pendingUpdates.map(([distinctId, update]) => limit(() => this.processGroupUpdate(update, distinctId)))
- )
+ const results = this.options.useBatchUpdates
+ ? await this.flushBatch(pendingWrites)
+ : await this.flushIndividual(pendingWrites)
this.groupCache.processDeferredEvictions()
- return []
+ // Drained after the writes so messages queued by fallback paths
+ // during this flush ride this flush's side effects too.
+ return [...results, ...this.drainPendingFlushResults()]
} catch (error) {
logger.error('Failed to flush group updates', {
error,
@@ -348,56 +423,156 @@ export class BatchWritingGroupStore implements GroupStore {
}
}
+ /**
+ * Write every dirty group individually with an optimistic version check.
+ */
+ private async flushIndividual(pendingWrites: PendingGroupWrite[]): Promise<GroupFlushResult[]> {
+ const limit = pLimit(this.options.maxConcurrentUpdates)
+ const results = await Promise.all(
+ pendingWrites.map(({ update, cacheKey }) => limit(() => this.processGroupUpdate(update, cacheKey)))
+ )
+ return results.filter((result): result is GroupFlushResult => result !== null)
+ }
+
+ /**
+ * Write all dirty groups in a single UNNEST statement with server-side
+ * jsonb merge semantics. Groups missing from the result (deleted or never
+ * created) fall back to the individual path, which creates them via the
+ * direct-upsert fallback. A failure of the whole statement falls back to
+ * individual optimistic writes of the full property view, so no captured
+ * delta is lost.
+ */
+ private async flushBatch(pendingWrites: PendingGroupWrite[]): Promise<GroupFlushResult[]> {
+ this.incrementDatabaseOperation('updateGroupsBatch')
+
+ let updatedGroups: Group[]
+ try {
+ updatedGroups = await this.groupRepository.updateGroupsBatch(
+ pendingWrites.map(({ update, propertiesToSet }) => ({
+ teamId: update.team_id,
+ groupTypeIndex: update.group_type_index,
+ groupKey: update.group_key,
+ propertiesToSet,
+ createdAt: update.created_at,
+ }))
+ )
+ } catch (error) {
+ logger.warn('⚠️', 'Batch group update failed, falling back to individual updates', {
+ count: pendingWrites.length,
+ error,
+ errorMessage: error instanceof Error ? error.message : String(error),
+ })
+ return await this.flushIndividual(pendingWrites)
+ }
+
+ // Key by the full row identity — unlike the cache key, which omits
+ // group_type_index — so two group types sharing a group key can never
+ // sync each other's row.
+ const rowIdentity = (group: { team_id: TeamId; group_type_index: GroupTypeIndex; group_key: string }) =>
+ `${group.team_id}:${group.group_type_index}:${group.group_key}`
+ const updatedByKey = new Map<string, Group>()
+ for (const group of updatedGroups) {
+ updatedByKey.set(rowIdentity(group), group)
+ }
+
+ const results: GroupFlushResult[] = []
+ const missingWrites: PendingGroupWrite[] = []
+
+ for (const pendingWrite of pendingWrites) {
+ const row = updatedByKey.get(rowIdentity(pendingWrite.update))
+ if (!row) {
+ missingWrites.push(pendingWrite)
+ continue
+ }
+
+ this.syncCacheEntryFromRow(pendingWrite.update, row)
+ results.push({
+ messages: [
+ this.clickhouseGroupRepository.buildUpsertMessage(
+ row.team_id,
+ row.group_type_index,
+ row.group_key,
+ row.group_properties,
+ row.created_at,
+ row.version
+ ),
+ ],
+ teamId: row.team_id,
+ groupTypeIndex: row.group_type_index,
+ groupKey: row.group_key,
+ })
+ }
+
+ if (missingWrites.length > 0) {
+ results.push(...(await this.flushIndividual(missingWrites)))
+ }
+
+ return results
+ }
+
+ /**
+ * Sync the cached entry with the authoritative row returned by the batch
+ * update, preserving any delta accumulated by concurrent batches since the
+ * flush captured this write.
+ */
+ private syncCacheEntryFromRow(update: GroupUpdate, row: Group): void {
+ const cached = this.groupCache.get(update.team_id, update.group_type_index, update.group_key)
+ const target = cached ?? update
+ target.group_properties = { ...row.group_properties, ...target.properties_to_set }
+ target.created_at = DateTime.min(target.created_at, row.created_at)
+ target.version = row.version
+ }
+
getFlushStats(): BatchWritingStoreFlushStats {
return this.groupCache.getFlushStats()
}
- private async processGroupUpdate(update: GroupUpdate, distinctId: string): Promise<void> {
+ private async processGroupUpdate(update: GroupUpdate, cacheKey: string): Promise<GroupFlushResult | null> {
try {
- await promiseRetry(
+ const message = await promiseRetry(
() => this.executeOptimisticUpdate(update),
'updateGroupOptimistically',
this.options.maxOptimisticUpdateRetries,
- this.options.optimisticUpdateRetryInterval,
- undefined,
- [MessageSizeTooLarge]
+ // Jitter the starting interval so pods that conflicted on the
+ // same group don't retry in lockstep and re-collide.
+ this.options.optimisticUpdateRetryInterval * (0.5 + Math.random())
)
+ if (!message) {
+ return null
+ }
+ return {
+ messages: [message],
+ teamId: update.team_id,
+ groupTypeIndex: update.group_type_index,
+ groupKey: update.group_key,
+ }
} catch (error) {
- await this.handleOptimisticUpdateFailure(error, update, distinctId)
+ await this.handleOptimisticUpdateFailure(error, update, cacheKey)
+ return null
}
}
- private async handleOptimisticUpdateFailure(
- error: unknown,
- update: GroupUpdate,
- distinctId: string
- ): Promise<void> {
- if (error instanceof MessageSizeTooLarge) {
- await emitIngestionWarning(this.outputs, update.team_id, {
- type: 'group_upsert_message_size_too_large',
- details: {
- groupTypeIndex: update.group_type_index,
- groupKey: update.group_key,
- distinctId: distinctId,
- },
- pipelineStep: 'group-store',
- })
- return
- }
-
- await this.fallbackToDirectUpsert(update, distinctId)
+ private async handleOptimisticUpdateFailure(error: unknown, update: GroupUpdate, cacheKey: string): Promise<void> {
+ logger.warn('⚠️', 'Optimistic group update failed after max retries', {
+ error,
+ teamId: update.team_id,
+ groupTypeIndex: update.group_type_index,
+ groupKey: update.group_key,
+ cacheKey,
+ })
+ await this.fallbackToDirectUpsert(update, cacheKey)
}
- private async fallbackToDirectUpsert(update: GroupUpdate, distinctId: string): Promise<void> {
+ private async fallbackToDirectUpsert(update: GroupUpdate, cacheKey: string): Promise<void> {
logger.warn('⚠️', 'Falling back to direct upsert after max retries', {
teamId: update.team_id,
groupTypeIndex: update.group_type_index,
groupKey: update.group_key,
- distinctId,
+ cacheKey,
})
// Remove from cache to prevent retry
- this.groupCache.delete(update.team_id, update.group_key)
+ this.groupCache.delete(update.team_id, update.group_type_index, update.group_key)
try {
await this.executeGroupUpsert(
@@ -461,26 +636,20 @@ export class BatchWritingGroupStore implements GroupStore {
const group = await this.getGroup(teamId, groupTypeIndex, groupKey, false, groupCache)
if (!group) {
- await this.executeGroupUpsert(
- teamId,
- groupTypeIndex,
- groupKey,
- properties,
- timestamp,
- false,
- 'batch-create',
- batchId
- )
+ await this.createGroup(teamId, groupTypeIndex, groupKey, properties, timestamp, batchId)
return
}
const propertiesUpdate = calculateUpdate(group.group_properties || {}, properties)
if (propertiesUpdate.updated) {
- groupCache.set(teamId, groupKey, {
+ groupCache.set(teamId, groupTypeIndex, groupKey, {
team_id: teamId,
group_type_index: groupTypeIndex,
group_key: groupKey,
group_properties: propertiesUpdate.properties,
+ // Accumulate the delta since the last DB sync — a flush in
+ // flight has already captured (and reset) the previous delta.
+ properties_to_set: { ...group.properties_to_set, ...propertiesUpdate.changedProperties },
created_at: group.created_at,
version: group.version,
needsWrite: true,
@@ -488,6 +657,61 @@ export class BatchWritingGroupStore implements GroupStore {
}
}
+ /**
+ * Create a group that the cache says doesn't exist. Runs without a
+ * wrapping transaction — the insert is a single ON CONFLICT DO NOTHING
+ * statement, so the transaction added round trips without atomicity value.
+ * A racing create surfaces as RaceConditionError, which handleUpsertError
+ * turns into a cache refresh and upsert retry.
+ */
+ private async createGroup(
+ teamId: TeamId,
+ groupTypeIndex: GroupTypeIndex,
+ groupKey: string,
+ properties: Properties,
+ timestamp: DateTime,
+ batchId: number
+ ): Promise<void> {
+ const createdAt = DateTime.min(DateTime.now(), timestamp)
+
+ this.incrementDatabaseOperation('insertGroup')
+ const insertedVersion = await this.groupRepository.insertGroup(
+ teamId,
+ groupTypeIndex,
+ groupKey,
+ properties,
+ createdAt,
+ {},
+ {}
+ )
+
+ this.groupCache.obtainForBatchId(batchId).set(teamId, groupTypeIndex, groupKey, {
+ team_id: teamId,
+ group_type_index: groupTypeIndex,
+ group_key: groupKey,
+ group_properties: properties,
+ properties_to_set: {},
+ created_at: createdAt,
+ version: insertedVersion,
+ needsWrite: false,
+ })
+
+ // The ClickHouse message rides the next flush's side effects instead
+ // of being awaited here: delivery reports on the downstream producer
+ // can take ~seconds under backpressure, and awaiting one inline
+ // serializes the per-distinct-id lane (observed in production with
+ // create-heavy migration traffic).
+ this.queueClickhouseMessage(
+ teamId,
+ groupTypeIndex,
+ groupKey,
+ properties,
+ createdAt,
+ insertedVersion,
+ 'batch-create'
+ )
+ }
+
private async executeGroupUpsert(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
@@ -517,7 +741,7 @@ export class BatchWritingGroupStore implements GroupStore {
)
if (propertiesUpdate.updated) {
- await this.upsertToClickhouse(
+ this.queueClickhouseMessage(
teamId,
groupTypeIndex,
groupKey,
@@ -529,7 +753,13 @@ export class BatchWritingGroupStore implements GroupStore {
}
}
- private async upsertToClickhouse(
+ /**
+ * Queue a group's ClickHouse message for the next flush, which returns it
+ * for side-effect production (awaited before the owning batch's offset
+ * commit). ReplacingMergeTree ordering by version makes produce order
+ * across flushes irrelevant.
+ */
+ private queueClickhouseMessage(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
groupKey: string,
@@ -537,16 +767,29 @@ export class BatchWritingGroupStore implements GroupStore {
createdAt: DateTime,
actualVersion: number,
source: string
- ): Promise<void> {
+ ): void {
this.incrementDatabaseOperation('upsertClickhouse' + (source ? `-${source}` : ''))
- await this.clickhouseGroupRepository.upsertGroup(
+ this.pendingFlushResults.push({
+ messages: [
+ this.clickhouseGroupRepository.buildUpsertMessage(
+ teamId,
+ groupTypeIndex,
+ groupKey,
+ properties,
+ createdAt,
+ actualVersion
+ ),
+ ],
teamId,
groupTypeIndex,
groupKey,
- properties,
- createdAt,
- actualVersion
- )
+ })
+ }
+
+ private drainPendingFlushResults(): GroupFlushResult[] {
+ const pending = this.pendingFlushResults
+ this.pendingFlushResults = []
+ return pending
}
private async executeUpsertTransaction(
@@ -593,11 +836,12 @@ export class BatchWritingGroupStore implements GroupStore {
expectedVersion,
tx
)
- groupCache?.set(teamId, groupKey, {
+ groupCache?.set(teamId, groupTypeIndex, groupKey, {
team_id: teamId,
group_type_index: groupTypeIndex,
group_key: groupKey,
group_properties: propertiesUpdate.properties,
+ properties_to_set: {},
created_at: createdAt,
version: actualVersion,
needsWrite: false,
@@ -660,7 +904,7 @@ export class BatchWritingGroupStore implements GroupStore {
return insertedVersion
}
- private async executeOptimisticUpdate(update: GroupUpdate): Promise<void> {
+ private async executeOptimisticUpdate(update: GroupUpdate): Promise<GroupClickhouseMessage | null> {
this.incrementDatabaseOperation('updateGroupOptimistically')
const actualVersion = await this.groupRepository.updateGroupOptimistically(
update.team_id,
@@ -674,16 +918,20 @@ export class BatchWritingGroupStore implements GroupStore {
)
if (actualVersion !== undefined) {
- await this.upsertToClickhouse(
+ // Keep the cached entry's version in sync with the row we just
+ // wrote, so the next flush of this entry doesn't CAS against a
+ // stale version and manufacture a conflict.
+ update.version = actualVersion
+ // The ClickHouse produce is returned to the caller and scheduled as
+ // a side effect after flush, so flush latency stays DB-only.
+ return this.clickhouseGroupRepository.buildUpsertMessage(
update.team_id,
update.group_type_index,
update.group_key,
update.group_properties,
update.created_at,
- actualVersion,
- 'optimistically'
+ actualVersion
)
- return
}
groupOptimisticUpdateConflictsPerBatchCounter.inc()
@@ -696,6 +944,16 @@ export class BatchWritingGroupStore implements GroupStore {
)
if (latestGroup) {
const propertiesUpdate = calculateUpdate(latestGroup.group_properties || {}, update.group_properties)
+ if (!propertiesUpdate.updated && update.created_at >= latestGroup.created_at) {
+ // The winning writer already persisted everything this update
+ // carries — common for hot groups receiving identical
+ // $group_set payloads across pods. Sync to the winning row and
+ // skip the write (and its ClickHouse produce) entirely.
+ update.group_properties = latestGroup.group_properties || {}
+ update.created_at = latestGroup.created_at
+ update.version = latestGroup.version
+ return null
+ }
if (propertiesUpdate.updated) {
update.group_properties = propertiesUpdate.properties
}
@@ -704,6 +962,120 @@ export class BatchWritingGroupStore implements GroupStore {
throw new Error('Optimistic update failed, will retry')
}
+ /**
+ * Best-effort cache warmer for the given group keys — one batched query
+ * instead of a single-row fetch per key. Callers fire this without
+ * awaiting it (mirrors prefetchPersons): transient persons-Postgres
+ * unavailability is swallowed here so the fire-and-forget copy can't
+ * crash the worker, while each per-key promise (awaited by getGroup)
+ * still rejects so consumers propagate the error and retry. Any other
+ * error is rethrown so it crashes loudly rather than being masked.
+ */
+ async prefetchGroups(
+ entries: { teamId: TeamId; groupTypeIndex: GroupTypeIndex; groupKey: string; batchId: number }[]
+ ): Promise<void> {
+ if (entries.length === 0) {
+ return
+ }
+
+ // Filter out entries that are already cached or have pending fetches.
+ const uncachedEntries: { teamId: TeamId; groupTypeIndex: GroupTypeIndex; groupKey: string; batchId: number }[] =
+ []
+ const seenKeys = new Set<string>()
+ for (const entry of entries) {
+ const key = `${entry.teamId}:${entry.groupTypeIndex}:${entry.groupKey}`
+ if (seenKeys.has(key)) {
+ continue
+ }
+ seenKeys.add(key)
+ if (this.groupCache.hasForBatch(entry.batchId, entry.teamId, entry.groupTypeIndex, entry.groupKey)) {
+ continue
+ }
+ if (this.groupCache.getFetchPromise(entry.teamId, entry.groupTypeIndex, entry.groupKey)) {
+ continue
+ }
+ uncachedEntries.push(entry)
+ }
+
+ if (uncachedEntries.length === 0) {
+ return
+ }
+
+ const prefetchBatchIds = new Set(uncachedEntries.map(({ batchId }) => batchId))
+ this.groupCache.trackPendingPrefetch(prefetchBatchIds)
+ this.incrementDatabaseOperation('prefetchGroups')
+
+ const batchFetchPromise = this.groupRepository
+ .fetchGroupsByKeys(uncachedEntries, 'ingestion/group-prefetch')
+ .then((rows) => {
+ const groupsByKey = new Map<string, GroupUpdate>()
+ for (const row of rows) {
+ groupsByKey.set(`${row.team_id}:${row.group_type_index}:${row.group_key}`, {
+ team_id: row.team_id,
+ group_type_index: row.group_type_index,
+ group_key: row.group_key,
+ group_properties: row.group_properties,
+ properties_to_set: {},
+ created_at: row.created_at,
+ version: row.version,
+ needsWrite: false,
+ })
+ }
+
+ // Cache all results (found groups and nulls for missing ones).
+ for (const { teamId, groupTypeIndex, groupKey, batchId } of uncachedEntries) {
+ // Caching under a released batchId would re-register it in
+ // the refcount tracking with nobody left to release it.
+ if (this.groupCache.isBatchReleasedWithPendingPrefetch(batchId)) {
+ continue
+ }
+ // Don't clobber an entry that appeared while the fetch was
+ // in flight (e.g. a group created inline by event processing).
+ if (this.groupCache.get(teamId, groupTypeIndex, groupKey) !== undefined) {
+ continue
+ }
+ this.groupCache.setForBatch(
+ batchId,
+ teamId,
+ groupTypeIndex,
+ groupKey,
+ groupsByKey.get(`${teamId}:${groupTypeIndex}:${groupKey}`) ?? null
+ )
+ }
+
+ return groupsByKey
+ })
+ .finally(() => {
+ for (const { teamId, groupTypeIndex, groupKey } of uncachedEntries) {
+ this.groupCache.deleteFetchPromise(teamId, groupTypeIndex, groupKey)
+ }
+ this.groupCache.finishPendingPrefetch(prefetchBatchIds)
+ })
+
+ // Register per-key promises so getGroup waits on the in-flight batch
+ // fetch instead of issuing its own single-row query. The throwaway
+ // catch only marks the promise handled so an unconsumed key can't
+ // become an unhandled rejection — awaiting consumers still observe
+ // the rejection.
+ for (const { teamId, groupTypeIndex, groupKey } of uncachedEntries) {
+ const keyPromise = batchFetchPromise.then(
+ (groupsByKey) => groupsByKey.get(`${teamId}:${groupTypeIndex}:${groupKey}`) ?? null
+ )
+ keyPromise.catch(() => {})
+ this.groupCache.setFetchPromise(teamId, groupTypeIndex, groupKey, keyPromise)
+ }
+
+ await batchFetchPromise.catch((error) => {
+ if (error?.isRetriable === true) {
+ logger.warn('⚠️', 'prefetchGroups failed on a retriable persons-Postgres error', {
+ error: String(error),
+ })
+ return
+ }
+ throw error
+ })
+ }
+
private async getGroup(
teamId: TeamId,
groupTypeIndex: GroupTypeIndex,
@@ -712,14 +1084,14 @@ export class BatchWritingGroupStore implements GroupStore {
groupCache: BatchBoundGroupCache | undefined,
tx?: GroupRepositoryTransaction
): Promise<GroupUpdate | null> {
- if (groupCache?.has(teamId, groupKey) && !forUpdate) {
- const cachedGroup = groupCache.get(teamId, groupKey)
+ if (groupCache?.has(teamId, groupTypeIndex, groupKey) && !forUpdate) {
+ const cachedGroup = groupCache.get(teamId, groupTypeIndex, groupKey)
if (cachedGroup !== undefined) {
return cachedGroup
}
}
- let fetchPromise = groupCache?.getFetchPromise(teamId, groupKey)
+ let fetchPromise = groupCache?.getFetchPromise(teamId, groupTypeIndex, groupKey)
if (!fetchPromise) {
groupFetchPromisesCacheOperationsCounter.inc({ operation: 'miss' })
fetchPromise = (async () => {
@@ -729,20 +1101,20 @@ export class BatchWritingGroupStore implements GroupStore {
const existingGroup = await repository.fetchGroup(teamId, groupTypeIndex, groupKey, { forUpdate })
if (existingGroup) {
const groupUpdate = fromGroup(existingGroup)
- groupCache?.set(teamId, groupKey, {
+ groupCache?.set(teamId, groupTypeIndex, groupKey, {
...groupUpdate,
needsWrite: false,
})
return groupUpdate
} else {
- groupCache?.set(teamId, groupKey, null)
+ groupCache?.set(teamId, groupTypeIndex, groupKey, null)
return null
}
} finally {
- groupCache?.deleteFetchPromise(teamId, groupKey)
+ groupCache?.deleteFetchPromise(teamId, groupTypeIndex, groupKey)
}
})()
- groupCache?.setFetchPromise(teamId, groupKey, fetchPromise)
+ groupCache?.setFetchPromise(teamId, groupTypeIndex, groupKey, fetchPromise)
} else {
groupFetchPromisesCacheOperationsCounter.inc({ operation: 'hit' })
}
@@ -759,20 +1131,9 @@ export class BatchWritingGroupStore implements GroupStore {
timestamp: DateTime,
batchId: number
): Promise<void> {
- if (error instanceof MessageSizeTooLarge) {
- await emitIngestionWarning(this.outputs, teamId, {
- type: 'group_upsert_message_size_too_large',
- details: {
- groupTypeIndex,
- groupKey,
- },
- pipelineStep: 'group-store',
- })
- return
- }
if (error instanceof RaceConditionError) {
// Remove from cache to prevent retry, the group was already created by another thread
- this.groupCache.delete(teamId, groupKey)
+ this.groupCache.delete(teamId, groupTypeIndex, groupKey)
return this.upsertGroup(teamId, projectId, groupTypeIndex, groupKey, properties, timestamp, batchId)
}
throw error
@@ -831,7 +1192,7 @@ export class BatchWritingGroupStore implements GroupStore {
this.metricEmissionTimer = undefined
}
- let dirtyCount = 0
+ let dirtyCount = this.pendingFlushResults.length
for (const [_, entry] of this.groupCache.entries()) {
if (entry && entry.needsWrite) {
dirtyCount++
diff --git a/nodejs/src/ingestion/common/groups/group-store-for-batch.ts b/nodejs/src/ingestion/common/groups/group-store-for-batch.ts
index 7ff368fe30c7..027c61c4195f 100644
--- a/nodejs/src/ingestion/common/groups/group-store-for-batch.ts
+++ b/nodejs/src/ingestion/common/groups/group-store-for-batch.ts
@@ -1,11 +1,10 @@
import { DateTime } from 'luxon'
-import { FlushResult } from '~/ingestion/common/persons/persons-store'
import { Properties } from '~/plugin-scaffold'
import { GroupTypeIndex, ProjectId, TeamId } from '~/types'
import { BatchWritingGroupStore } from './batch-writing-group-store'
-import { CacheMetrics, GroupStore } from './group-store.interface'
+import { CacheMetrics, GroupFlushResult, GroupStore } from './group-store.interface'
export type GroupStoreForBatch = Omit<GroupStore, 'upsertGroup' | 'releaseBatch' | 'getFlushStats'> & {
upsertGroup(
@@ -16,6 +15,15 @@ export type GroupStoreForBatch = Omit<GroupStore, 'upsertGroup' | 'releaseBatch'
properties: Properties,
timestamp: DateTime
): Promise<void>
+ /**
+ * Best-effort cache warmer: fetches all given group keys in one batched
+ * query. Each entry may carry its own batchId for cache eviction tracking,
+ * allowing a single DB fetch to service entries belonging to different
+ * concurrent batches.
+ */
+ prefetchGroups(
+ entries: { teamId: TeamId; groupTypeIndex: GroupTypeIndex; groupKey: string; batchId: number }[]
+ ): Promise<void>
readonly batchId: number
}
@@ -36,11 +44,17 @@ export class BatchBoundGroupStore implements GroupStoreForBatch {
return this.store.upsertGroup(teamId, projectId, groupTypeIndex, groupKey, properties, timestamp, this.batchId)
}
+ prefetchGroups(
+ entries: { teamId: TeamId; groupTypeIndex: GroupTypeIndex; groupKey: string; batchId: number }[]
+ ): Promise<void> {
+ return this.store.prefetchGroups(entries)
+ }
+
getCacheMetrics(): CacheMetrics {
return this.store.getCacheMetrics()
}
- flush(): Promise<FlushResult[]> {
+ flush(): Promise<GroupFlushResult[]> {
return this.store.flush()
}
diff --git a/nodejs/src/ingestion/common/groups/group-store.interface.ts b/nodejs/src/ingestion/common/groups/group-store.interface.ts
index 50b7991d0ddf..16a592e318a3 100644
--- a/nodejs/src/ingestion/common/groups/group-store.interface.ts
+++ b/nodejs/src/ingestion/common/groups/group-store.interface.ts
@@ -1,5 +1,6 @@
import { DateTime } from 'luxon'
+import { GroupClickhouseMessage } from '~/common/groups/repositories/clickhouse-group-repository'
import { BatchWritingStore } from '~/ingestion/common/stores/batch-writing-store'
import { Properties } from '~/plugin-scaffold'
import { GroupTypeIndex, ProjectId, TeamId } from '~/types'
@@ -9,7 +10,14 @@ export interface CacheMetrics {
cacheMisses: number
}
-export interface GroupStore extends BatchWritingStore {
+export type GroupFlushResult = {
+ messages: GroupClickhouseMessage[]
+ teamId: TeamId
+ groupTypeIndex: GroupTypeIndex
+ groupKey: string
+}
+
+export interface GroupStore extends BatchWritingStore<GroupFlushResult> {
/**
* Stop any background work (e.g., periodic metric emission) and flush
* remaining accumulated metrics. Called on graceful shutdown. Does NOT
diff --git a/nodejs/src/ingestion/common/groups/group-update.ts b/nodejs/src/ingestion/common/groups/group-update.ts
index a62e8ace24c8..b3e51f3e0455 100644
--- a/nodejs/src/ingestion/common/groups/group-update.ts
+++ b/nodejs/src/ingestion/common/groups/group-update.ts
@@ -1,3 +1,4 @@
+import equal from 'fast-deep-equal'
import { DateTime } from 'luxon'
import { Properties } from '~/plugin-scaffold'
@@ -8,6 +9,12 @@ export interface GroupUpdate {
group_type_index: GroupTypeIndex
group_key: string
group_properties: Properties
+ /**
+ * Keys set by events since this entry was last synced with the database.
+ * This is the delta that batched flushes merge server-side (jsonb `||`);
+ * `group_properties` remains the full merged view for cache reads.
+ */
+ properties_to_set: Properties
created_at: DateTime
version: number
needsWrite: boolean
@@ -16,6 +23,8 @@ export interface GroupUpdate {
export interface PropertiesUpdate {
updated: boolean
properties: Properties
+ /** The subset of incoming properties that actually changed. */
+ changedProperties: Properties
}
export function fromGroup(group: Group): GroupUpdate {
@@ -24,6 +33,7 @@ export function fromGroup(group: Group): GroupUpdate {
group_type_index: group.group_type_index,
group_key: group.group_key,
group_properties: group.group_properties,
+ properties_to_set: {},
created_at: group.created_at,
version: group.version,
needsWrite: false,
@@ -34,6 +44,7 @@ export function calculateUpdate(currentProperties: Properties, properties: Prope
const result: PropertiesUpdate = {
updated: false,
properties: { ...currentProperties },
+ changedProperties: {},
}
// Ideally we'd keep track of event timestamps, for when properties were updated
@@ -45,9 +56,14 @@ export function calculateUpdate(currentProperties: Properties, properties: Prope
// So instead we just process properties updates based on ingestion time,
// i.e. always update if value has changed.
Object.entries(properties).forEach(([key, value]) => {
- if (!(key in result.properties) || value != result.properties[key]) {
+ // Deep equality, not reference equality: object/array values arrive as fresh
+ // JSON parses on every event, so a reference compare would mark every group
+ // with a nested property as changed on every event, causing constant no-op
+ // writes, version bumps, and cross-pod update conflicts.
+ if (!(key in result.properties) || !equal(value, result.properties[key])) {
result.updated = true
result.properties[key] = value
+ result.changedProperties[key] = value
}
})
return result
diff --git a/nodejs/src/ingestion/common/persons/persons-store.ts b/nodejs/src/ingestion/common/persons/persons-store.ts
index 2b7518bfbdf4..1555f7816993 100644
--- a/nodejs/src/ingestion/common/persons/persons-store.ts
+++ b/nodejs/src/ingestion/common/persons/persons-store.ts
@@ -16,7 +16,7 @@ export type FlushResult = {
uuid?: string
}
-export interface PersonsStore extends BatchWritingStore {
+export interface PersonsStore extends BatchWritingStore<FlushResult> {
/**
* Executes a function within a transaction
* @param description - Description of the transaction for logging
diff --git a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts
index 6452e578efbe..c79f7be92066 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.test.ts
@@ -1,9 +1,9 @@
-import { INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
+import { GROUPS_OUTPUT, INGESTION_WARNINGS_OUTPUT } from '~/common/outputs'
import { PERSONS_OUTPUT, PERSON_DISTINCT_IDS_OUTPUT, PERSON_MERGE_EVENTS_OUTPUT } from '~/common/outputs'
import { MessageSizeTooLarge } from '~/common/utils/db/error'
import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'
+import { GroupFlushResult } from '~/ingestion/common/groups/group-store.interface'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
-import { PersonOutputs } from '~/ingestion/common/persons/person-context'
import { FlushResult, PersonsStore } from '~/ingestion/common/persons/persons-store'
import {
batchStoreFlushCacheEntriesHistogram,
@@ -19,7 +19,11 @@ import { AfterBatchInput } from '~/ingestion/framework/batching-pipeline'
import { isOkResult, ok } from '~/ingestion/framework/results'
import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
-import { FlushBatchStoresStepConfig, createFlushBatchStoresStep } from './flush-batch-stores-step'
+import {
+ FlushBatchStoresOutputs,
+ FlushBatchStoresStepConfig,
+ createFlushBatchStoresStep,
+} from './flush-batch-stores-step'
jest.mock('~/ingestion/common/ingestion-warnings', () => ({
emitIngestionWarning: jest.fn(),
@@ -39,7 +43,7 @@ jest.mock('~/ingestion/common/stores/metrics', () => ({
describe('flush-batch-stores-step', () => {
let mockPersonsStore: jest.Mocked<PersonsStore>
let mockGroupStore: jest.Mocked<BatchWritingGroupStore>
- let mockOutputs: PersonOutputs
+ let mockOutputs: FlushBatchStoresOutputs
let storesConfig: FlushBatchStoresStepConfig
beforeEach(() => {
@@ -70,6 +74,7 @@ describe('flush-batch-stores-step', () => {
| typeof PERSON_DISTINCT_IDS_OUTPUT
| typeof INGESTION_WARNINGS_OUTPUT
| typeof PERSON_MERGE_EVENTS_OUTPUT
+ | typeof GROUPS_OUTPUT
>()
storesConfig = {
@@ -303,6 +308,67 @@ describe('flush-batch-stores-step', () => {
})
})
+ it('should produce group store flush results as side effects', async () => {
+ const groupResults: GroupFlushResult[] = [
+ {
+ messages: [{ output: GROUPS_OUTPUT, value: Buffer.from('group1') }],
+ teamId: 1,
+ groupTypeIndex: 0,
+ groupKey: 'org-1',
+ },
+ ]
+
+ mockPersonsStore.flush.mockResolvedValue([])
+ mockGroupStore.flush.mockResolvedValue(groupResults)
+ const produceSpy = jest.spyOn(mockOutputs, 'produce')
+
+ const result = await step(makeInput())
+
+ expect(isOkResult(result)).toBe(true)
+ if (isOkResult(result)) {
+ expect(result.sideEffects).toHaveLength(1)
+ }
+ expect(produceSpy).toHaveBeenCalledWith(GROUPS_OUTPUT, {
+ key: null,
+ value: Buffer.from('group1'),
+ teamId: 1,
+ })
+ })
+
+ it('should emit a group-specific warning when a group message is too large', async () => {
+ const groupResults: GroupFlushResult[] = [
+ {
+ messages: [{ output: GROUPS_OUTPUT, value: Buffer.from('group1') }],
+ teamId: 1,
+ groupTypeIndex: 0,
+ groupKey: 'org-1',
+ },
+ ]
+
+ mockPersonsStore.flush.mockResolvedValue([])
+ mockGroupStore.flush.mockResolvedValue(groupResults)
+ jest.spyOn(mockOutputs, 'produce').mockRejectedValue(
+ new MessageSizeTooLarge('test', new Error('too large'))
+ )
+
+ const result = await step(makeInput())
+
+ expect(isOkResult(result)).toBe(true)
+ if (isOkResult(result)) {
+ expect(result.sideEffects).toHaveLength(1)
+ await result.sideEffects[0]
+ }
+
+ expect(emitIngestionWarning).toHaveBeenCalledWith(mockOutputs, 1, {
+ type: 'group_upsert_message_size_too_large',
+ details: {
+ groupTypeIndex: 0,
+ groupKey: 'org-1',
+ },
+ pipelineStep: 'flush',
+ })
+ })
+
it('should propagate other Kafka produce errors', async () => {
const personMessages: FlushResult[] = [
{
diff --git a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts
index c1d9cde64a62..393ccf87e37a 100644
--- a/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts
+++ b/nodejs/src/ingestion/common/steps/event-processing/flush-batch-stores-step.ts
@@ -1,6 +1,9 @@
+import { GroupsOutput } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { MessageSizeTooLarge } from '~/common/utils/db/error'
import { logger } from '~/common/utils/logger'
import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'
+import { GroupFlushResult } from '~/ingestion/common/groups/group-store.interface'
import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'
import { PersonOutputs } from '~/ingestion/common/persons/person-context'
import { FlushResult, PersonsStore } from '~/ingestion/common/persons/persons-store'
@@ -18,10 +21,12 @@ import {
import { AfterBatchStep } from '~/ingestion/framework/batching-pipeline'
import { ok } from '~/ingestion/framework/results'
+export type FlushBatchStoresOutputs = PersonOutputs & IngestionOutputs<GroupsOutput>
+
export interface FlushBatchStoresStepConfig {
personsStore: PersonsStore
groupStore: BatchWritingGroupStore
- outputs: PersonOutputs
+ outputs: FlushBatchStoresOutputs
}
type BatchStoreName = 'person' | 'group'
@@ -77,7 +82,10 @@ export function createFlushBatchStoresStep<TOutput, COutput, CBatch, R extends s
})
// Create Kafka produce promises for all person/group store updates
- const producePromises = createProducePromises(personsStoreMessages, outputs)
+ const producePromises = [
+ ...createPersonProducePromises(personsStoreMessages, outputs),
+ ...createGroupProducePromises(groupResults, outputs),
+ ]
return ok(input, producePromises)
} catch (error) {
@@ -96,7 +104,10 @@ export function createFlushBatchStoresStep<TOutput, COutput, CBatch, R extends s
}
}
-async function flushStore(store: BatchStoreName, batchWritingStore: BatchWritingStore): Promise<FlushResult[]> {
+async function flushStore<TFlushResult extends { messages: unknown[] }>(
+ store: BatchStoreName,
+ batchWritingStore: BatchWritingStore<TFlushResult>
+): Promise<TFlushResult[]> {
const flushStats = batchWritingStore.getFlushStats()
batchStoreFlushDirtyEntriesHistogram.observe({ store }, flushStats.dirtyEntryCount)
batchStoreFlushReferencedBatchesHistogram.observe({ store }, flushStats.referencedBatchCount)
@@ -119,7 +130,7 @@ async function flushStore(store: BatchStoreName, batchWritingStore: BatchWriting
}
}
-function countFlushResultMessages(flushResults: FlushResult[]): number {
+function countFlushResultMessages(flushResults: { messages: unknown[] }[]): number {
return flushResults.reduce((count, record) => count + record.messages.length, 0)
}
@@ -129,7 +140,7 @@ function countFlushResultMessages(flushResults: FlushResult[]): number {
* - MessageSizeTooLarge: Emits ingestion warning (non-fatal)
* - Other errors: Propagated to fail the side effect
*/
-function createProducePromises(personsStoreMessages: FlushResult[], outputs: PersonOutputs): Promise<unknown>[] {
+function createPersonProducePromises(personsStoreMessages: FlushResult[], outputs: PersonOutputs): Promise<unknown>[] {
const promises: Promise<unknown>[] = []
for (const record of personsStoreMessages) {
@@ -178,3 +189,61 @@ function createProducePromises(personsStoreMessages: FlushResult[], outputs: Per
return promises
}
+
+/**
+ * Creates Kafka produce promises for all group store flush results, mirroring
+ * the person handling: MessageSizeTooLarge emits a group-specific ingestion
+ * warning (non-fatal), other errors fail the side effect.
+ *
+ * Exported so callers outside the batch pipeline (e.g. the ingestion API
+ * server's shutdown cleanup) can produce a bare `groupStore.flush()` result
+ * without duplicating the MessageSizeTooLarge handling.
+ */
+export function createGroupProducePromises(
+ groupResults: GroupFlushResult[],
+ outputs: FlushBatchStoresOutputs
+): Promise<unknown>[] {
+ const promises: Promise<unknown>[] = []
+
+ for (const record of groupResults) {
+ for (const message of record.messages) {
+ const promise = outputs
+ .produce(message.output, {
+ key: null,
+ value: message.value,
+ teamId: record.teamId,
+ })
+ .catch((error) => {
+ if (error instanceof MessageSizeTooLarge) {
+ logger.warn('🪣', 'flushBatchStoresStep: Group message size too large', {
+ output: message.output,
+ teamId: record.teamId,
+ groupTypeIndex: record.groupTypeIndex,
+ groupKey: record.groupKey,
+ })
+ return emitIngestionWarning(outputs, record.teamId, {
+ type: 'group_upsert_message_size_too_large',
+ details: {
+ groupTypeIndex: record.groupTypeIndex,
+ groupKey: record.groupKey,
+ },
+ pipelineStep: 'flush',
+ })
+ } else {
+ logger.error('❌', 'flushBatchStoresStep: Failed to produce group message', {
+ error,
+ output: message.output,
+ teamId: record.teamId,
+ groupTypeIndex: record.groupTypeIndex,
+ groupKey: record.groupKey,
+ })
+ throw error
+ }
+ })
+
+ promises.push(promise)
+ }
+ }
+
+ return promises
+}
diff --git a/nodejs/src/ingestion/common/stores/batch-writing-store.ts b/nodejs/src/ingestion/common/stores/batch-writing-store.ts
index 4808a36a1dd8..1ec93e3cd939 100644
--- a/nodejs/src/ingestion/common/stores/batch-writing-store.ts
+++ b/nodejs/src/ingestion/common/stores/batch-writing-store.ts
@@ -1,12 +1,10 @@
-import { FlushResult } from '~/ingestion/common/persons/persons-store'
-
export interface BatchWritingStoreFlushStats {
dirtyEntryCount: number
referencedBatchCount: number
cacheEntryCount: number
}
-export interface BatchWritingStore {
+export interface BatchWritingStore<TFlushResult = unknown> {
/*
* Returns a point-in-time summary of entries that would be captured by
* flush(), plus the batch IDs that currently reference those dirty entries.
@@ -17,7 +15,7 @@ export interface BatchWritingStore {
* Flushes all batch data that needs to be written
* Returns Kafka messages that need to be sent
*/
- flush(): Promise<FlushResult[]>
+ flush(): Promise<TFlushResult[]>
/*
* Releases cache entries associated with the given batch ID.
diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.ts
index fe68c9c27bf5..f425be3e6d84 100644
--- a/nodejs/src/ingestion/config.ts
+++ b/nodejs/src/ingestion/config.ts
@@ -155,9 +155,11 @@ export type IngestionConsumerConfig = {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: string
// Group batch writing config
+ GROUP_BATCH_WRITING_USE_BATCH_UPDATES: boolean
GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: number
GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: number
GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: number
+ GROUPS_PREFETCH_ENABLED: boolean
// Event overflow config
EVENT_OVERFLOW_BUCKET_CAPACITY: number
@@ -268,9 +270,11 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {
PERSON_MERGE_EVENTS_TEAM_ALLOWLIST: '2',
// Group batch writing config
+ GROUP_BATCH_WRITING_USE_BATCH_UPDATES: false,
GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES: 10,
GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES: 5,
GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS: 50,
+ GROUPS_PREFETCH_ENABLED: false,
// Event overflow config
EVENT_OVERFLOW_BUCKET_CAPACITY: 1000,
diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.ts
index 00b22f658a20..46e8f17e0a47 100644
--- a/nodejs/src/ingestion/ingestion-consumer.ts
+++ b/nodejs/src/ingestion/ingestion-consumer.ts
@@ -219,16 +219,12 @@ export class IngestionConsumer {
updateAllProperties: this.config.PERSON_PROPERTIES_UPDATE_ALL,
})
- this.groupStore = new BatchWritingGroupStore(
- this.deps.outputs,
- this.deps.groupRepository,
- this.deps.clickhouseGroupRepository,
- {
- maxConcurrentUpdates: this.config.GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES,
- maxOptimisticUpdateRetries: this.config.GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,
- optimisticUpdateRetryInterval: this.config.GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
- }
- )
+ this.groupStore = new BatchWritingGroupStore(this.deps.groupRepository, this.deps.clickhouseGroupRepository, {
+ useBatchUpdates: this.config.GROUP_BATCH_WRITING_USE_BATCH_UPDATES,
+ maxConcurrentUpdates: this.config.GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES,
+ maxOptimisticUpdateRetries: this.config.GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,
+ optimisticUpdateRetryInterval: this.config.GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
+ })
this.kafkaConsumer = createKafkaConsumer({
groupId: this.groupId,
@@ -276,6 +272,7 @@ export class IngestionConsumer {
overflowMode: this.config.INGESTION_OVERFLOW_MODE,
preservePartitionLocality: this.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
+ groupsPrefetchEnabled: this.config.GROUPS_PREFETCH_ENABLED,
cdpHogWatcherSampleRate: this.config.CDP_HOG_WATCHER_SAMPLE_RATE,
outputs,
perDistinctIdOptions: {
diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
index 036e01e32b95..0ad258d4736e 100644
--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts
@@ -73,6 +73,7 @@ export interface JoinedIngestionPipelineConfig {
overflowMode: IngestionOverflowMode
preservePartitionLocality: boolean
personsPrefetchEnabled: boolean
+ groupsPrefetchEnabled: boolean
cdpHogWatcherSampleRate: number
outputs: IngestionOutputs<
| EventOutput
@@ -153,6 +154,7 @@ export function createJoinedIngestionPipeline<
overflowMode,
preservePartitionLocality,
personsPrefetchEnabled,
+ groupsPrefetchEnabled,
cdpHogWatcherSampleRate,
outputs,
perDistinctIdOptions,
@@ -195,6 +197,8 @@ export function createJoinedIngestionPipeline<
overflowLaneTTLRefreshService,
featureFlagCalledDedupService,
personsPrefetchEnabled,
+ groupsPrefetchEnabled,
+ groupTypeManager,
flagCalledPersonlessDefaultTeams: perDistinctIdOptions.FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS,
hogTransformer,
cdpHogWatcherSampleRate,
diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
index 68fe792d0e92..ec61c99f79fe 100644
--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts
@@ -1,5 +1,6 @@
import { Message } from 'node-rdkafka'
+import { GroupTypeManager } from '~/common/groups/group-type-manager'
import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'
@@ -7,6 +8,7 @@ import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-mana
import { EventFilterManager } from '~/ingestion/common/event-filters'
import { EventFiltersBatchAppMetrics } from '~/ingestion/common/event-filters/batch-app-metrics'
import { FeatureFlagCalledDedupService } from '~/ingestion/common/feature-flag-called-dedup/feature-flag-called-dedup-service'
+import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'
import { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'
import { PersonsStoreForBatch } from '~/ingestion/common/persons/persons-store-for-batch'
import { createApplyEventFiltersStep } from '~/ingestion/common/steps/event-filters-steps'
@@ -23,6 +25,7 @@ import {
import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'
import { createPrefetchHogFunctionsStep } from '~/ingestion/common/steps/event-processing/prefetch-hog-functions-step'
import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'
+import { prefetchGroupsStep } from '~/ingestion/pipelines/analytics/steps/prefetchGroupsStep'
import { prefetchPersonsStep } from '~/ingestion/pipelines/analytics/steps/prefetchPersonsStep'
import { processPersonlessDistinctIdsChunkStep } from '~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep'
import { PluginEvent } from '~/plugin-scaffold'
@@ -35,6 +38,7 @@ export interface PostTeamPreprocessingSubpipelineInput {
team: Team
eventFiltersBatchAppMetrics: EventFiltersBatchAppMetrics
personsStoreForBatch: PersonsStoreForBatch
+ groupStoreForBatch: GroupStoreForBatch
}
export interface PostTeamPreprocessingSubpipelineConfig {
@@ -48,6 +52,8 @@ export interface PostTeamPreprocessingSubpipelineConfig {
overflowLaneTTLRefreshService?: OverflowRedirectService
featureFlagCalledDedupService?: FeatureFlagCalledDedupService
personsPrefetchEnabled: boolean
+ groupsPrefetchEnabled: boolean
+ groupTypeManager: GroupTypeManager
flagCalledPersonlessDefaultTeams: string
hogTransformer: HogTransformer
cdpHogWatcherSampleRate: number
@@ -68,6 +74,8 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
overflowLaneTTLRefreshService,
featureFlagCalledDedupService,
personsPrefetchEnabled,
+ groupsPrefetchEnabled,
+ groupTypeManager,
flagCalledPersonlessDefaultTeams,
hogTransformer,
cdpHogWatcherSampleRate,
@@ -109,6 +117,9 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr
// no-op — transient persons-Postgres failures are swallowed inside prefetchPersons so
// they can't surface as an unhandled rejection and crash the worker.
.pipeChunk(prefetchPersonsStep(personsPrefetchEnabled))
+ // Same best-effort, fire-and-forget cache warming for groups: one
+ // batched fetch for the chunk's $groupidentify group keys.
+ .pipeChunk(prefetchGroupsStep(groupTypeManager, groupsPrefetchEnabled))
// Batch insert personless distinct IDs after prefetch (uses prefetch cache).
// This step awaits its DB write, so retry transient persons-Postgres failures
// (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop.
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchGroupsStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchGroupsStep.test.ts
new file mode 100644
index 000000000000..2bd64bc55146
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchGroupsStep.test.ts
@@ -0,0 +1,77 @@
+import { GroupTypeManager } from '~/common/groups/group-type-manager'
+import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'
+import { PipelineResultType, isOkResult } from '~/ingestion/framework/results'
+import { prefetchGroupsStep } from '~/ingestion/pipelines/analytics/steps/prefetchGroupsStep'
+import { PipelineEvent, Team } from '~/types'
+
+type TestInput = { event: PipelineEvent; team: Team; groupStoreForBatch: GroupStoreForBatch }
+
+function createStore(batchId: number): GroupStoreForBatch {
+ return {
+ batchId,
+ prefetchGroups: jest.fn().mockResolvedValue(undefined),
+ } as unknown as GroupStoreForBatch
+}
+
+function createInput(
+ eventName: string,
+ properties: Record<string, any>,
+ teamId: number,
+ groupStoreForBatch: GroupStoreForBatch
+): TestInput {
+ return {
+ event: { event: eventName, properties } as unknown as PipelineEvent,
+ team: { id: teamId, project_id: teamId } as unknown as Team,
+ groupStoreForBatch,
+ }
+}
+
+describe('prefetchGroupsStep', () => {
+ let groupTypeManager: GroupTypeManager
+
+ beforeEach(() => {
+ const groupTypes: Record<string, number> = { organization: 0, project: 1 }
+ groupTypeManager = {
+ lookupGroupTypeIndex: jest
+ .fn()
+ .mockImplementation((_projectId: number, groupType: string) =>
+ Promise.resolve(Object.hasOwn(groupTypes, groupType) ? groupTypes[groupType] : null)
+ ),
+ } as unknown as GroupTypeManager
+ })
+
+ it('prefetches only $groupidentify events with known group types', async () => {
+ const store = createStore(1)
+ const step = prefetchGroupsStep<TestInput>(groupTypeManager, true)
+
+ const results = await step([
+ createInput('$groupidentify', { $group_type: 'organization', $group_key: 'org-1' }, 3, store),
+ createInput('$pageview', { $group_type: 'organization', $group_key: 'org-2' }, 3, store),
+ // Unknown group type — would require an insert, so it's skipped.
+ createInput('$groupidentify', { $group_type: 'brand-new-type', $group_key: 'x' }, 3, store),
+ // Inherited object property names must not resolve to a group type.
+ createInput('$groupidentify', { $group_type: '__proto__', $group_key: 'evil' }, 3, store),
+ createInput('$groupidentify', { $group_type: 'project', $group_key: 42 }, 4, store),
+ createInput('$groupidentify', { $group_type: 'organization' }, 3, store),
+ ])
+
+ expect(results.every((result) => result.type === PipelineResultType.OK)).toBe(true)
+ expect(results.filter(isOkResult)).toHaveLength(6)
+ expect(store.prefetchGroups).toHaveBeenCalledWith([
+ { teamId: 3, groupTypeIndex: 0, groupKey: 'org-1', batchId: 1 },
+ { teamId: 4, groupTypeIndex: 1, groupKey: '42', batchId: 1 },
+ ])
+ })
+
+ it('passes events through without prefetching when disabled', async () => {
+ const store = createStore(1)
+ const step = prefetchGroupsStep<TestInput>(groupTypeManager, false)
+
+ const results = await step([
+ createInput('$groupidentify', { $group_type: 'organization', $group_key: 'org-1' }, 3, store),
+ ])
+
+ expect(results.map((result) => result.type)).toEqual([PipelineResultType.OK])
+ expect(store.prefetchGroups).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/prefetchGroupsStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchGroupsStep.ts
new file mode 100644
index 000000000000..7f9c5101356e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/analytics/steps/prefetchGroupsStep.ts
@@ -0,0 +1,65 @@
+import { GroupTypeManager } from '~/common/groups/group-type-manager'
+import { sanitizeString } from '~/common/utils/db/utils'
+import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'
+import { PipelineResult, ok } from '~/ingestion/framework/results'
+import { GroupTypeIndex, PipelineEvent, Team, TeamId } from '~/types'
+
+type PrefetchGroupsStepInput = { event: PipelineEvent; team: Team; groupStoreForBatch: GroupStoreForBatch }
+
+type PrefetchGroupEntry = { teamId: TeamId; groupTypeIndex: GroupTypeIndex; groupKey: string; batchId: number }
+
+/**
+ * Warms the group cache for all $groupidentify events in the chunk with one
+ * batched query per store, instead of a single-row fetch per group key during
+ * event processing. Group type indexes are resolved through the
+ * GroupTypeManager's cached mapping only — unknown group types (which would
+ * require an insert) are skipped and handled by processGroupsStep.
+ */
+export function prefetchGroupsStep<T extends PrefetchGroupsStepInput>(
+ groupTypeManager: GroupTypeManager,
+ enabled: boolean
+) {
+ return async function prefetchGroupsStep(events: T[]): Promise<PipelineResult<T>[]> {
+ if (enabled && events.length > 0) {
+ // Events in a chunk may come from different Kafka batches (due to the feed primitive).
+ // Group by batch store so each store only receives entries it owns. Fire without
+ // awaiting — getGroup will wait on the pending promises if it needs data that's
+ // still being fetched.
+ const entriesByStore = new Map<GroupStoreForBatch, PrefetchGroupEntry[]>()
+
+ for (const event of events) {
+ if (event.event.event !== '$groupidentify') {
+ continue
+ }
+ const properties = event.event.properties ?? {}
+ const groupType = properties['$group_type']
+ const groupKey = properties['$group_key']
+ if (!groupType || !groupKey) {
+ continue
+ }
+
+ const groupTypeIndex = await groupTypeManager.lookupGroupTypeIndex(event.team.project_id, groupType)
+ if (groupTypeIndex === null) {
+ continue
+ }
+
+ let entries = entriesByStore.get(event.groupStoreForBatch)
+ if (!entries) {
+ entries = []
+ entriesByStore.set(event.groupStoreForBatch, entries)
+ }
+ entries.push({
+ teamId: event.team.id,
+ groupTypeIndex,
+ groupKey: sanitizeString(String(groupKey)),
+ batchId: event.groupStoreForBatch.batchId,
+ })
+ }
+
+ for (const [store, entries] of entriesByStore) {
+ void store.prefetchGroups(entries)
+ }
+ }
+ return events.map((event) => ok(event))
+ }
+}
diff --git a/nodejs/src/servers/ingestion-api-server.test.ts b/nodejs/src/servers/ingestion-api-server.test.ts
index aa9c289c44f2..11d3014324a9 100644
--- a/nodejs/src/servers/ingestion-api-server.test.ts
+++ b/nodejs/src/servers/ingestion-api-server.test.ts
@@ -1,4 +1,8 @@
+import { GROUPS_OUTPUT } from '~/common/outputs'
+import { GroupFlushResult } from '~/ingestion/common/groups/group-store.interface'
+
import { IngestBatchResponse, SerializedKafkaMessage } from '../ingestion/api/types'
+import { CleanupResources } from './base-server'
import { IngestionApiServer } from './ingestion-api-server'
describe('IngestionApiServer', () => {
@@ -86,4 +90,38 @@ describe('IngestionApiServer', () => {
expect(isHealthy().status).toBe('ok')
expect(stopSpy).not.toHaveBeenCalled()
})
+
+ describe('cleanup', () => {
+ // groupStore.flush() no longer produces ClickHouse messages itself (see
+ // batch-writing-group-store.ts) — it returns them for the caller to
+ // produce, mirroring personsStore.flushAndProduceMessages(). The shutdown
+ // cleanup path must produce them itself or dirty entries flushed at
+ // shutdown (e.g. a pod drain mid-batch) are written to Postgres but never
+ // reach ClickHouse, and a redelivery of the same batch finds no property
+ // diff and never regenerates the message.
+ it('produces ClickHouse messages returned by groupStore.flush() during shutdown cleanup', async () => {
+ const flushResult: GroupFlushResult = {
+ messages: [{ output: GROUPS_OUTPUT, value: Buffer.from('group-payload') }],
+ teamId: 1,
+ groupTypeIndex: 0,
+ groupKey: 'test-group',
+ }
+ const groupStore = {
+ flush: jest.fn().mockResolvedValue([flushResult]),
+ shutdown: jest.fn().mockResolvedValue(undefined),
+ }
+ const ingestionOutputs = { produce: jest.fn().mockResolvedValue(undefined) }
+ ;(server as any).groupStore = groupStore
+ ;(server as any).ingestionOutputs = ingestionOutputs
+
+ const cleanup: CleanupResources = (server as any).getCleanupResources()
+ await cleanup.additionalCleanup?.()
+
+ expect(ingestionOutputs.produce).toHaveBeenCalledWith(GROUPS_OUTPUT, {
+ key: null,
+ value: flushResult.messages[0].value,
+ teamId: flushResult.teamId,
+ })
+ })
+ })
})
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.ts
index 29c9e321338d..978c59f288a0 100644
--- a/nodejs/src/servers/ingestion-api-server.ts
+++ b/nodejs/src/servers/ingestion-api-server.ts
@@ -37,6 +37,10 @@ import {
import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'
import { effectivePersonMergeEventsEnabled } from '~/ingestion/common/persons/person-merge-event'
import { PersonsStore } from '~/ingestion/common/persons/persons-store'
+import {
+ FlushBatchStoresOutputs,
+ createGroupProducePromises,
+} from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
import { createOkContext } from '~/ingestion/framework/helpers'
import { TopHog } from '~/ingestion/framework/tophog'
import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'
@@ -165,6 +169,10 @@ export class IngestionApiServer implements NodeServer {
private pubsub?: PubSub
private personsStore?: BatchWritingPersonsStore
private groupStore?: BatchWritingGroupStore
+ // Held so shutdown cleanup can produce ClickHouse messages returned by a
+ // bare groupStore.flush() — the store itself no longer holds outputs
+ // (moved to caller-side production so create and flush share one path).
+ private ingestionOutputs?: FlushBatchStoresOutputs
private joinedPipeline!: ReturnType<
typeof createJoinedIngestionPipeline<JoinedIngestionPipelineInput, JoinedIngestionPipelineContext>
@@ -280,6 +288,7 @@ export class IngestionApiServer implements NodeServer {
this.config
)
const ingestionOutputs = createOutputsRegistry().build(this.ingestionProducerRegistry, this.config)
+ this.ingestionOutputs = ingestionOutputs
const clickhouseGroupRepository = new ClickhouseGroupRepository(ingestionOutputs)
const topicFailures = await ingestionOutputs.checkTopics()
@@ -345,7 +354,8 @@ export class IngestionApiServer implements NodeServer {
})
const personsStore: PersonsStore = this.personsStore
- this.groupStore = new BatchWritingGroupStore(ingestionOutputs, groupRepository, clickhouseGroupRepository, {
+ this.groupStore = new BatchWritingGroupStore(groupRepository, clickhouseGroupRepository, {
+ useBatchUpdates: this.config.GROUP_BATCH_WRITING_USE_BATCH_UPDATES,
maxConcurrentUpdates: this.config.GROUP_BATCH_WRITING_MAX_CONCURRENT_UPDATES,
maxOptimisticUpdateRetries: this.config.GROUP_BATCH_WRITING_MAX_OPTIMISTIC_UPDATE_RETRIES,
optimisticUpdateRetryInterval: this.config.GROUP_BATCH_WRITING_OPTIMISTIC_UPDATE_RETRY_INTERVAL_MS,
@@ -365,6 +375,7 @@ export class IngestionApiServer implements NodeServer {
overflowMode: this.config.INGESTION_OVERFLOW_MODE,
preservePartitionLocality: this.config.INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY,
personsPrefetchEnabled: this.config.PERSONS_PREFETCH_ENABLED,
+ groupsPrefetchEnabled: this.config.GROUPS_PREFETCH_ENABLED,
cdpHogWatcherSampleRate: this.config.CDP_HOG_WATCHER_SAMPLE_RATE,
outputs: ingestionOutputs,
perDistinctIdOptions: {
@@ -546,7 +557,15 @@ export class IngestionApiServer implements NodeServer {
await this.personsStore.shutdown()
}
if (this.groupStore) {
- await this.groupStore.flush()
+ const groupFlushResults = await this.groupStore.flush()
+ // flush() returns messages for the caller to produce (it no
+ // longer awaits ClickHouse delivery inline) — mirror
+ // personsStore.flushAndProduceMessages() so a drain at
+ // shutdown doesn't write Postgres but silently drop the
+ // corresponding ClickHouse row.
+ if (groupFlushResults.length > 0 && this.ingestionOutputs) {
+ await Promise.all(createGroupProducePromises(groupFlushResults, this.ingestionOutputs))
+ }
await this.groupStore.shutdown()
}
this.cookielessManager?.shutdown()
diff --git a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
index f5fe6df81b4a..61bc63ee477f 100644
--- a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
+++ b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts
@@ -4,9 +4,11 @@ import { DlqOutput, IngestionWarningsOutput } from '~/common/outputs'
import { parseJSON } from '~/common/utils/json-parse'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-group-store'
-import { PersonOutputs } from '~/ingestion/common/persons/person-context'
import { FlushResult, PersonsStore } from '~/ingestion/common/persons/persons-store'
-import { createFlushBatchStoresStep } from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
+import {
+ FlushBatchStoresOutputs,
+ createFlushBatchStoresStep,
+} from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'
import { BatchWritingStore, BatchWritingStoreFlushStats } from '~/ingestion/common/stores/batch-writing-store'
import { BatchingPipeline, BeforeBatchInput, FeedResult } from '~/ingestion/framework/batching-pipeline'
import { newBatchingPipeline } from '~/ingestion/framework/builders'
@@ -372,7 +374,7 @@ class Harness {
createFlushBatchStoresStep({
personsStore: this.personsStore as unknown as PersonsStore,
groupStore: this.groupStore as unknown as BatchWritingGroupStore,
- outputs: this.outputs as unknown as PersonOutputs,
+ outputs: this.outputs as unknown as FlushBatchStoresOutputs,
})
)
.pipe(recordAfterBatchStep),