Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

use redis stream to aggregate events

Thiago Araujo da Silva84f6e5d8cd12
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 6be602e79a..910219ff37 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -412,6 +412,17 @@ The gate has to sit at the call site because **a `DROP` aggregation does not bou
- Adding a new label means adding it to the allowlist in `telemetry-attributes.ts`. Only add **bounded** keys (fixed enums / static route templates), and document why.
- `http.route` must be the parameterized template (`req.routeOptions.url`), never the raw request path.
+### PostHog Product Analytics
+
+Separate from the OpenTelemetry metrics above. `src/services/telemetry/telemetry-service.ts` captures product events; the events listed in `POSTHOG_AGGREGATED_EVENTS` are too high-volume to send one-per-occurrence, so they are buffered in Redis and rolled up by the `TelemetryAggregatedEvents` cron every 10 minutes.
+
+**Buffered events live in one Redis stream per (event type, bucket)** — `telemetry-agg-stream:<event>:<bucket>`, 30 buckets, bucket chosen by hashing the `distinctId`. Two invariants hold that shape together:
+
+- **Never discover buffered events by pattern.** The previous layout wrote one Redis key per event and the cron found them with `getKeysByPattern` per (event type, bucket), so each run cost `events × buckets` full keyspace walks — 240 walks over a ~440k-key keyspace, ~73s of Redis engine CPU every 10 minutes, and it grew every time an event was added to the aggregation list. The stream layout is read by key, so the cost tracks the number of pending events instead of the size of the keyspace. Adding an event type to `POSTHOG_AGGREGATED_EVENTS` must stay free of keyspace scans.
+- **A `distinctId` must always hash to the same bucket.** Each shard is aggregated independently, so a `distinctId` split across shards produces one aggregated PostHog event per shard instead of one overall.
+
+Draining is at-least-once: a shard is trimmed (`XTRIM MINID`) only after its batch has been handed to PostHog, so a failed run retries on the next tick. Growth is bounded by the `MAXLEN` cap on write, not by a TTL. Nothing reads the pre-stream keys, so a deploy that changes this layout drops whatever is still buffered — acceptable for product analytics, and the reason there is no migration path to maintain.
+
### Database Configuration
Knex config in `src/db/knexfile.ts`. Loads `.env.migration` then `.env`. Supports `DB_CONNECTION_URI` or individual host/port/user/name/password fields. Optional SSL via `DB_ROOT_CERT` (base64-encoded CA cert). Connection pool: min 2, max 10. Migrations table: `infisical_migrations`. Separate audit log DB supported via `auditlog-migration:*` scripts. ClickHouse for analytics (optional).
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a045c0f411..de93917fc5 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -166,9 +166,8 @@ export const KeyStorePrefixes = {
`lockout:identity:${identityId}:${authMethod}:*` as const,
IdentityLockoutStatePattern: (identityId: string) => `lockout:identity:${identityId}:*` as const,
- TelemetryEvent: (event: string, bucketId: string, distinctId: string, uuid: string) =>
- `telemetry-event-${event}-${bucketId}-${distinctId}-${uuid}` as const,
- TelemetryEventByBucketPattern: (event: string, bucketId: string) => `telemetry-event-${event}-${bucketId}-*` as const,
+ TelemetryAggregatedEventStream: (event: string, bucketId: string) =>
+ `telemetry-agg-stream:${event}:${bucketId}` as const,
AuditLogStreamFlushDebounce: (streamId: string) => `audit-log-stream:${streamId}:flush-debounce` as const,
AuditLogIngestConsumerLock: "audit-log-ingest:consumer-lock" as const
@@ -223,7 +222,6 @@ export const KeyStoreTtls = {
StepUpMfaLockoutInSeconds: 300, // 5 minutes - temporary lockout after too many failed step-up attempts
TelemetryGroupIdentifyInSeconds: 3600, // 1 hour
TelemetryAuditLogsViewedInSeconds: 3600, // 1 hour
- TelemetryAggregatedEventInSeconds: 1800, // 30 minutes
SecretEtagInSeconds: 900, // 15 minutes
PkiAcmeNonceInSeconds: 300, // 5 minutes
GatewayRelayCredentialInSeconds: 600, // 10 minutes - TURN credential lifetime
diff --git a/backend/src/services/telemetry/telemetry-service.test.ts b/backend/src/services/telemetry/telemetry-service.test.ts
new file mode 100644
index 0000000000..6532a4b979
--- /dev/null
+++ b/backend/src/services/telemetry/telemetry-service.test.ts
@@ -0,0 +1,200 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { PostHogEventTypes } from "./telemetry-types";
+
+const mockConfig = {
+ isProductionMode: true,
+ TELEMETRY_ENABLED: true,
+ POSTHOG_PROJECT_API_KEY: "phc_test",
+ POSTHOG_HOST: "https://posthog.test",
+ INFISICAL_CLOUD: true,
+ INFISICAL_DEDICATED: false,
+ INTERNAL_REGION: "us"
+};
+
+vi.mock("@app/lib/config/env", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/lib/config/env")>()),
+ getConfig: () => mockConfig
+}));
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
+
+vi.mock("@fastify/request-context", () => ({
+ requestContext: { get: vi.fn(() => undefined) }
+}));
+
+const postHogClient = {
+ capture: vi.fn(),
+ groupIdentify: vi.fn(),
+ identify: vi.fn(),
+ shutdown: vi.fn(async () => undefined)
+};
+
+vi.mock("posthog-node", () => ({
+ PostHog: vi.fn(() => postHogClient)
+}));
+
+// eslint-disable-next-line import/first
+import { telemetryServiceFactory } from "./telemetry-service";
+
+// streamCollect returns [entryId, ["data", json]] tuples; the consumer parses fields[1].
+const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => ({
+ entries: payloads.map((p, i) => [`${i + 1}-0`, ["data", JSON.stringify(p)]] as [string, string[]]),
+ lastId
+});
+
+const pulledEvent = (overrides: Record<string, unknown> = {}) => ({
+ distinctId: "user-1",
+ event: PostHogEventTypes.SecretPulled,
+ properties: { numberOfSecrets: 3, environment: "prod" },
+ organizationId: "org-1",
+ ...overrides
+});
+
+const createHarness = () => {
+ const keyStore = {
+ incrementBy: vi.fn<(key: string, value: number) => Promise<number>>(async () => 1),
+ setItemWithExpiryNX: vi.fn<() => Promise<"OK" | null>>(async () => null),
+ streamAdd: vi.fn<
+ (key: string, id: string, fieldValue: Record<string, string>, maxLen?: number) => Promise<string | null>
+ >(async () => "1-0"),
+ streamCollect: vi.fn<(key: string) => Promise<{ entries: [string, string[]][]; lastId: string | null }>>(
+ async () => ({ entries: [], lastId: null })
+ ),
+ streamTrim: vi.fn<(key: string, minId: string, inclusive?: boolean) => Promise<number>>(async () => 0)
+ };
+
+ const telemetryService = telemetryServiceFactory({
+ keyStore: keyStore as never,
+ licenseService: { getInstanceType: vi.fn(() => "cloud"), getPlan: vi.fn() } as never,
+ orgDAL: { findOrgById: vi.fn() } as never,
+ emailDomainDAL: { find: vi.fn(async () => []) } as never
+ });
+
+ return { keyStore, telemetryService };
+};
+
+describe("telemetry aggregated event storage", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test("appends an aggregated event to its shard stream instead of a per-event key", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ await telemetryService.sendPostHogEvents(pulledEvent() as never);
+
+ expect(keyStore.streamAdd).toHaveBeenCalledTimes(1);
+ const [key, id, fields, maxLen] = keyStore.streamAdd.mock.calls[0];
+ expect(key).toBe(
+ `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${telemetryService.getBucketForDistinctId("user-1")}`
+ );
+ expect(id).toBe("*");
+ expect(maxLen).toBeGreaterThan(0);
+ expect(JSON.parse(fields.data)).toMatchObject({
+ distinctId: "user-1",
+ event: PostHogEventTypes.SecretPulled,
+ organizationId: "org-1"
+ });
+ // The event must not be captured directly — it is aggregated by the cron.
+ expect(postHogClient.capture).not.toHaveBeenCalled();
+ });
+
+ test("all events for one distinctId land on the same shard", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ await telemetryService.sendPostHogEvents(pulledEvent({ properties: { numberOfSecrets: 1 } }) as never);
+ await telemetryService.sendPostHogEvents(pulledEvent({ properties: { numberOfSecrets: 2 } }) as never);
+
+ const keys = keyStore.streamAdd.mock.calls.map((call) => call[0]);
+ expect(new Set(keys).size).toBe(1);
+ });
+
+ test("drains a shard by key, then trims what it published", async () => {
+ const { keyStore, telemetryService } = createHarness();
+ const bucketId = telemetryService.getBucketForDistinctId("user-1");
+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;
+
+ keyStore.streamCollect.mockImplementation(async (key) =>
+ key === streamKey
+ ? collectResult([pulledEvent(), pulledEvent({ properties: { numberOfSecrets: 4 } })], "7-0")
+ : { entries: [], lastId: null }
+ );
+
+ await telemetryService.processAggregatedEvents();
+
+ const captures = postHogClient.capture.mock.calls.map(([arg]) => arg as Record<string, unknown>);
+ expect(captures).toHaveLength(1);
+ expect(captures[0]).toMatchObject({
+ event: `${PostHogEventTypes.SecretPulled} aggregated`,
+ distinctId: "user-1"
+ });
+ expect(captures[0].properties).toMatchObject({ count: 2, numberOfSecrets: 7, orgId: "org-1" });
+
+ expect(keyStore.streamTrim).toHaveBeenCalledTimes(1);
+ expect(keyStore.streamTrim).toHaveBeenCalledWith(streamKey, "7-0", true);
+ });
+
+ test("attempts the hourly groupIdentify claim once per org, not once per actor", async () => {
+ const { keyStore, telemetryService } = createHarness();
+ keyStore.setItemWithExpiryNX.mockResolvedValue("OK");
+
+ // Four actors, two orgs, spread across whichever shards their distinctIds hash to.
+ const byShard = new Map<string, Record<string, unknown>[]>();
+ for (const [distinctId, organizationId] of [
+ ["user-1", "org-1"],
+ ["user-2", "org-1"],
+ ["user-3", "org-2"],
+ ["user-4", "org-2"]
+ ]) {
+ const shard = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${telemetryService.getBucketForDistinctId(distinctId)}`;
+ byShard.set(shard, [...(byShard.get(shard) ?? []), pulledEvent({ distinctId, organizationId })]);
+ }
+
+ keyStore.streamCollect.mockImplementation(async (key) => {
+ const payloads = byShard.get(key);
+ return payloads ? collectResult(payloads) : { entries: [], lastId: null };
+ });
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(postHogClient.capture).toHaveBeenCalledTimes(4);
+ expect(keyStore.setItemWithExpiryNX).toHaveBeenCalledTimes(2);
+ expect(postHogClient.groupIdentify).toHaveBeenCalledTimes(2);
+ expect(
+ postHogClient.groupIdentify.mock.calls.map(([arg]) => (arg as { groupKey: string }).groupKey).sort()
+ ).toEqual(["org-1", "org-2"]);
+ });
+
+ test("leaves the shard untrimmed when publishing fails, so the batch is retried", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([pulledEvent()]));
+ postHogClient.capture.mockImplementationOnce(() => {
+ throw new Error("posthog down");
+ });
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(keyStore.streamTrim).not.toHaveBeenCalled();
+ });
+
+ test("skips an unparseable entry rather than dropping the whole shard", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ keyStore.streamCollect.mockResolvedValueOnce({
+ entries: [
+ ["1-0", ["data", "{not json"]],
+ ["2-0", ["data", JSON.stringify(pulledEvent())]]
+ ],
+ lastId: "2-0"
+ });
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(postHogClient.capture).toHaveBeenCalledTimes(1);
+ expect(keyStore.streamTrim).toHaveBeenCalledWith(expect.any(String), "2-0", true);
+ });
+});
diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.ts
index 9de5a1bd5c..e4715b3b63 100644
--- a/backend/src/services/telemetry/telemetry-service.ts
+++ b/backend/src/services/telemetry/telemetry-service.ts
@@ -50,6 +50,9 @@ const TELEMETRY_BUCKET_NAMES = Array.from(
(_, i) => `bucket-${i.toString().padStart(2, "0")}`
);
+const TELEMETRY_EVENT_STREAM_BATCH_SIZE = 10_000;
+const TELEMETRY_EVENT_STREAM_MAX_ENTRIES = 50_000;
+
type AggregatedEventData = Record<string, unknown>;
type SingleEventData = {
distinctId: string;
@@ -63,7 +66,7 @@ export type TTelemetryServiceFactory = ReturnType<typeof telemetryServiceFactory
export type TTelemetryServiceFactoryDep = {
keyStore: Pick<
TKeyStoreFactory,
- "incrementBy" | "deleteItemsByKeyIn" | "setItemWithExpiry" | "setItemWithExpiryNX" | "getKeysByPattern" | "getItems"
+ "incrementBy" | "setItemWithExpiryNX" | "streamAdd" | "streamCollect" | "streamTrim"
>;
licenseService: Pick<TLicenseServiceFactory, "getInstanceType" | "getPlan">;
orgDAL: Pick<TOrgDALFactory, "findOrgById">;
@@ -81,10 +84,8 @@ const getBucketForDistinctId = (distinctId: string): string => {
return TELEMETRY_BUCKET_NAMES[bucketIndex];
};
-export const createTelemetryEventKey = (event: string, distinctId: string): string => {
- const bucketId = getBucketForDistinctId(distinctId);
- return KeyStorePrefixes.TelemetryEvent(event, bucketId, distinctId, crypto.nativeCrypto.randomUUID());
-};
+const getTelemetryEventStreamKey = (event: string, distinctId: string): string =>
+ KeyStorePrefixes.TelemetryAggregatedEventStream(event, getBucketForDistinctId(distinctId));
export enum DeploymentType {
USCloud = "us-cloud",
@@ -319,18 +320,15 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
const resolvedOrgName = event.organizationName ?? requestContext.get(RequestContextKey.OrgName);
if (POSTHOG_AGGREGATED_EVENTS.includes(event.event)) {
- const eventKey = createTelemetryEventKey(event.event, event.distinctId);
- await keyStore.setItemWithExpiry(
- eventKey,
- KeyStoreTtls.TelemetryAggregatedEventInSeconds,
- JSON.stringify({
+ await keyStore.streamAdd(getTelemetryEventStreamKey(event.event, event.distinctId), "*", {
+ data: JSON.stringify({
distinctId: event.distinctId,
event: event.event,
properties: event.properties,
organizationId: event.organizationId,
...(resolvedOrgName ? { organizationName: resolvedOrgName } : {})
})
- );
+ });
} else {
// Skip groupIdentify entirely when the event is marked anonymous.
//
@@ -461,118 +459,132 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
return aggregatedData;
};
- const processBucketEvents = async (eventType: string, bucketId: string) => {
- if (!postHog) return 0;
+ const parseEventPayloads = (payloads: (string | null)[], context: string): SingleEventData[] => {
+ const parsed: SingleEventData[] = [];
+ for (const payload of payloads) {
+ if (payload) {
+ try {
+ parsed.push(JSON.parse(payload) as SingleEventData);
+ } catch (error) {
+ logger.error(error, `Skipping unparseable telemetry event [${context}]`);
+ }
+ }
+ }
+ return parsed;
+ };
- try {
- const bucketPattern = KeyStorePrefixes.TelemetryEventByBucketPattern(eventType, bucketId);
- const bucketKeys = await keyStore.getKeysByPattern(bucketPattern);
+ const publishAggregatedEvents = async (
+ eventType: string,
+ events: SingleEventData[],
+ orgsIdentifyAttempted: Set<string>
+ ) => {
+ if (!postHog || events.length === 0) return;
- if (bucketKeys.length === 0) return 0;
+ const eventsGrouped = new Map<string, SingleEventData[]>();
- const bucketEvents = await keyStore.getItems(bucketKeys);
- let bucketEventsParsed: SingleEventData[] = [];
+ const breakdownDimensions = AGGREGATION_BREAKDOWN_DIMENSIONS[eventType as PostHogEventTypes] || [];
- try {
- bucketEventsParsed = bucketEvents
- .filter((event) => event !== null)
- .map((event) => JSON.parse(event as string) as SingleEventData);
- } catch (error) {
- logger.error(error, `Failed to parse bucket events for ${eventType} in ${bucketId}`);
- return 0;
+ events.forEach((event) => {
+ const breakdownValues: Record<string, string> = {};
+ if (breakdownDimensions.length > 0 && event.properties) {
+ const props = event.properties as Record<string, unknown>;
+ for (const dim of breakdownDimensions) {
+ if (props[dim] !== undefined && props[dim] !== null) {
+ breakdownValues[dim] = String(props[dim]);
+ }
+ }
}
+ const key = JSON.stringify({ id: event.distinctId, org: event.organizationId, ...breakdownValues });
+ if (!eventsGrouped.has(key)) {
+ eventsGrouped.set(key, []);
+ }
+ eventsGrouped.get(key)!.push(event);
+ });
- const eventsGrouped = new Map<string, SingleEventData[]>();
-
- const breakdownDimensions = AGGREGATION_BREAKDOWN_DIMENSIONS[eventType as PostHogEventTypes] || [];
+ const instanceId = await getInstanceId();
- bucketEventsParsed.forEach((event) => {
- const breakdownValues: Record<string, string> = {};
- if (breakdownDimensions.length > 0 && event.properties) {
- const props = event.properties as Record<string, unknown>;
- for (const dim of breakdownDimensions) {
- if (props[dim] !== undefined && props[dim] !== null) {
- breakdownValues[dim] = String(props[dim]);
- }
+ for (const [eventsKey, groupedEvents] of eventsGrouped) {
+ const key = JSON.parse(eventsKey) as { id: string; org?: string; [dim: string]: string | undefined };
+ if (key.org && !orgsIdentifyAttempted.has(key.org)) {
+ orgsIdentifyAttempted.add(key.org);
+ try {
+ const groupIdentifyCacheKey = KeyStorePrefixes.TelemetryGroupIdentify(key.org);
+ // eslint-disable-next-line no-await-in-loop
+ const wasSet = await keyStore.setItemWithExpiryNX(
+ groupIdentifyCacheKey,
+ KeyStoreTtls.TelemetryGroupIdentifyInSeconds,
+ "1"
+ );
+ if (wasSet) {
+ // eslint-disable-next-line no-await-in-loop
+ const groupProperties = await getOrgGroupProperties(key.org, groupedEvents[0]?.organizationName);
+ postHog.groupIdentify({
+ groupType: "organization",
+ groupKey: key.org,
+ properties: groupProperties,
+ distinctId: key.id
+ });
}
+ } catch (error) {
+ logger.error(error, "Failed to identify PostHog organization");
}
- const key = JSON.stringify({ id: event.distinctId, org: event.organizationId, ...breakdownValues });
- if (!eventsGrouped.has(key)) {
- eventsGrouped.set(key, []);
+ }
+ const properties = aggregateGroupProperties(groupedEvents, breakdownDimensions);
+
+ for (const dim of breakdownDimensions) {
+ if (key[dim] !== undefined) {
+ properties[dim] = key[dim];
}
- eventsGrouped.get(key)!.push(event);
- });
+ }
- if (eventsGrouped.size === 0) return 0;
+ if (key.org) {
+ properties.orgId = key.org;
+ }
- // Cache org group properties per orgId to avoid redundant DB/API calls
- // when multiple users share the same org within a bucket
- const orgPropertiesCache = new Map<string, Record<string, unknown>>();
+ if (instanceId) {
+ properties.instanceId = instanceId;
+ }
- const instanceId = await getInstanceId();
+ postHog.capture({
+ event: `${eventType} aggregated`,
+ distinctId: key.id,
+ properties,
+ ...(key.org ? { groups: { organization: key.org } } : {})
+ });
+ }
+ };
- for (const [eventsKey, events] of eventsGrouped) {
- const key = JSON.parse(eventsKey) as { id: string; org?: string; [dim: string]: string | undefined };
- if (key.org) {
- try {
- // Dedup groupIdentify across all paths: only fire once per org per hour
- const groupIdentifyCacheKey = KeyStorePrefixes.TelemetryGroupIdentify(key.org);
- // eslint-disable-next-line no-await-in-loop
- const wasSet = await keyStore.setItemWithExpiryNX(
- groupIdentifyCacheKey,
- KeyStoreTtls.TelemetryGroupIdentifyInSeconds,
- "1"
- );
- if (wasSet) {
- let groupProperties = orgPropertiesCache.get(key.org);
- if (!groupProperties) {
- const orgName = events[0]?.organizationName;
- // eslint-disable-next-line no-await-in-loop
- groupProperties = await getOrgGroupProperties(key.org, orgName);
- orgPropertiesCache.set(key.org, groupProperties);
- }
- postHog.groupIdentify({
- groupType: "organization",
- groupKey: key.org,
- properties: groupProperties,
- distinctId: key.id
- });
- }
- } catch (error) {
- logger.error(error, "Failed to identify PostHog organization");
- }
- }
- const properties = aggregateGroupProperties(events, breakdownDimensions);
+ const processBucketEvents = async (eventType: string, bucketId: string, orgsIdentifyAttempted: Set<string>) => {
+ if (!postHog) return 0;
- // Attach breakdown dimension values as flat properties on the aggregated event
- for (const dim of breakdownDimensions) {
- if (key[dim] !== undefined) {
- properties[dim] = key[dim];
- }
- }
+ const streamKey = KeyStorePrefixes.TelemetryAggregatedEventStream(eventType, bucketId);
- // Always attach orgId as a flat property so aggregated events are filterable by organization
- if (key.org) {
- properties.orgId = key.org;
- }
+ try {
+ const { entries, lastId } = await keyStore.streamCollect(
+ streamKey,
+ TELEMETRY_EVENT_STREAM_BATCH_SIZE,
+ TELEMETRY_EVENT_STREAM_MAX_ENTRIES
+ );
- if (instanceId) {
- properties.instanceId = instanceId;
- }
+ if (entries.length === 0 || !lastId) return 0;
- postHog.capture({
- event: `${eventType} aggregated`,
- distinctId: key.id,
- properties,
- ...(key.org ? { groups: { organization: key.org } } : {})
- });
+ if (entries.length >= TELEMETRY_EVENT_STREAM_MAX_ENTRIES) {
+ logger.warn(
+ `Telemetry aggregation hit the collection ceiling for bucket ${bucketId} of ${eventType} [collected=${entries.length}] [maxEntries=${TELEMETRY_EVENT_STREAM_MAX_ENTRIES}] — the shard is backing up; the oldest entries risk being dropped by the Redis MAXLEN cap`
+ );
}
- // Clean up processed data for this bucket
- await keyStore.deleteItemsByKeyIn(bucketKeys);
+ const events = parseEventPayloads(
+ entries.map(([, fields]) => fields[1]),
+ `event=${eventType} bucket=${bucketId}`
+ );
+
+ await publishAggregatedEvents(eventType, events, orgsIdentifyAttempted);
+
+ await keyStore.streamTrim(streamKey, lastId, true);
- logger.info(`Processed ${bucketEventsParsed.length} events from bucket ${bucketId} for ${eventType}`);
- return bucketEventsParsed.length;
+ logger.info(`Processed ${events.length} events from bucket ${bucketId} for ${eventType}`);
+ return events.length;
} catch (error) {
logger.error(error, `Failed to process bucket ${bucketId} for ${eventType}`);
return 0;
@@ -584,6 +596,8 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
const processAggregatedEvents = async () => {
if (!postHog) return;
+ const orgsIdentifyAttempted = new Set<string>();
+
for (const eventType of POSTHOG_AGGREGATED_EVENTS) {
let totalProcessed = 0;
logger.info(`Starting bucket processing for ${eventType}`);
@@ -591,7 +605,9 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
for (let i = 0; i < TELEMETRY_BUCKET_NAMES.length; i += BUCKET_CONCURRENCY) {
const batch = TELEMETRY_BUCKET_NAMES.slice(i, i + BUCKET_CONCURRENCY);
// eslint-disable-next-line no-await-in-loop
- const results = await Promise.all(batch.map((bucketId) => processBucketEvents(eventType, bucketId)));
+ const results = await Promise.all(
+ batch.map((bucketId) => processBucketEvents(eventType, bucketId, orgsIdentifyAttempted))
+ );
totalProcessed += results.reduce((sum, n) => sum + n, 0);
}