Skip to content

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

keep event bounded

Thiago Araujo da Silva577822aabdb8
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 84e28c4089..17d9486a73 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -421,7 +421,14 @@ Separate from the OpenTelemetry metrics above. `src/services/telemetry/telemetry
- **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 the PostHog client, so a run that throws before that point retries the whole batch on the next tick. Growth is bounded by the `MAXLEN` cap on write (100k entries per shard), not by a TTL, and one run drains at most 50k entries per shard, so a backlog is worked off over several ticks instead of being pulled into the cron's memory at once. 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.
+Draining is at-least-once: a shard is trimmed (`XTRIM MINID`) only after its batch has been handed to the PostHog client, so a run that throws before that point retries the whole batch on the next tick. One run drains at most 50k entries per shard, so a backlog is worked off over several ticks instead of being pulled into the cron's memory at once.
+
+**Two independent bounds keep a shard from growing without limit, and both are load-bearing:**
+
+- **Count**, on the write path — `MAXLEN ~` 100k entries per shard.
+- **Age**, at the top of every cron run — each shard is trimmed to a 30-minute retention window before it is read. This trim sits *outside* the drain's error scope deliberately: a publish path that throws on every tick still has to age entries out, or the shard parks at its `MAXLEN` cap with nothing bounding how long buffered analytics sits in Redis. It stands in for the TTL the pre-stream per-event keys carried, and it is why a broken drain costs 30 minutes of product analytics instead of unbounded Redis memory.
+
+Shards are reached only by iterating `POSTHOG_AGGREGATED_EVENTS` × the 30 buckets, so **removing an event type from that list orphans its shards** — nothing trims them and nothing expires them. Leave the event in the list for one release so the cron drains it, or delete `telemetry-agg-stream:<event>:*` by hand; the same applies to lowering the bucket count, and to rolling back past this layout. 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
diff --git a/backend/src/services/telemetry/telemetry-service.test.ts b/backend/src/services/telemetry/telemetry-service.test.ts
index 6532a4b979..117864bb9e 100644
--- a/backend/src/services/telemetry/telemetry-service.test.ts
+++ b/backend/src/services/telemetry/telemetry-service.test.ts
@@ -37,7 +37,11 @@ vi.mock("posthog-node", () => ({
}));
// eslint-disable-next-line import/first
-import { telemetryServiceFactory } from "./telemetry-service";
+import { POSTHOG_AGGREGATED_EVENTS, telemetryServiceFactory } from "./telemetry-service";
+
+const RETENTION_MS = 30 * 60 * 1000;
+const BUCKET_COUNT = 30;
+const SHARD_COUNT = POSTHOG_AGGREGATED_EVENTS.length * BUCKET_COUNT;
// streamCollect returns [entryId, ["data", json]] tuples; the consumer parses fields[1].
const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => ({
@@ -45,6 +49,13 @@ const collectResult = (payloads: Record<string, unknown>[], lastId = "9-0") => (
lastId
});
+// The drain trim passes `inclusive`; the retention trim that runs on every shard does not.
+const drainTrims = (keyStore: { streamTrim: { mock: { calls: unknown[][] } } }) =>
+ keyStore.streamTrim.mock.calls.filter((call) => call[2] === true);
+
+const retentionTrims = (keyStore: { streamTrim: { mock: { calls: unknown[][] } } }) =>
+ keyStore.streamTrim.mock.calls.filter((call) => call[2] === undefined) as [string, string][];
+
const pulledEvent = (overrides: Record<string, unknown> = {}) => ({
distinctId: "user-1",
event: PostHogEventTypes.SecretPulled,
@@ -133,8 +144,7 @@ describe("telemetry aggregated event storage", () => {
});
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);
+ expect(drainTrims(keyStore)).toEqual([[streamKey, "7-0", true]]);
});
test("attempts the hourly groupIdentify claim once per org, not once per actor", async () => {
@@ -178,7 +188,7 @@ describe("telemetry aggregated event storage", () => {
await telemetryService.processAggregatedEvents();
- expect(keyStore.streamTrim).not.toHaveBeenCalled();
+ expect(drainTrims(keyStore)).toHaveLength(0);
});
test("skips an unparseable entry rather than dropping the whole shard", async () => {
@@ -197,4 +207,59 @@ describe("telemetry aggregated event storage", () => {
expect(postHogClient.capture).toHaveBeenCalledTimes(1);
expect(keyStore.streamTrim).toHaveBeenCalledWith(expect.any(String), "2-0", true);
});
+
+ test("ages every shard out to the retention window on each run", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ const startedAt = Date.now();
+ await telemetryService.processAggregatedEvents();
+ const trims = retentionTrims(keyStore);
+
+ // Exactly one trim per (event type, bucket), covering every bucket.
+ expect(trims).toHaveLength(SHARD_COUNT);
+ expect(new Set(trims.map(([key]) => key)).size).toBe(SHARD_COUNT);
+ expect(new Set(trims.map(([key]) => key.split(":").pop())).size).toBe(BUCKET_COUNT);
+
+ for (const [, minId] of trims) {
+ const [timestamp, sequence] = minId.split("-");
+ expect(sequence).toBe("0");
+ expect(Number(timestamp)).toBeGreaterThanOrEqual(startedAt - RETENTION_MS);
+ expect(Number(timestamp)).toBeLessThanOrEqual(Date.now() - RETENTION_MS);
+ }
+ });
+
+ test("ages the shard out even when publishing fails", async () => {
+ const { keyStore, telemetryService } = createHarness();
+
+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([pulledEvent()]));
+ postHogClient.capture.mockImplementationOnce(() => {
+ throw new Error("posthog down");
+ });
+
+ await telemetryService.processAggregatedEvents();
+
+ // Retention must not be coupled to the drain: a shard whose publish throws on every tick would
+ // otherwise grow until MAXLEN evicts it, with nothing bounding how long it sits in Redis.
+ expect(drainTrims(keyStore)).toHaveLength(0);
+ expect(retentionTrims(keyStore)).toHaveLength(SHARD_COUNT);
+ });
+
+ test("drains a shard whose retention trim fails", async () => {
+ const { keyStore, telemetryService } = createHarness();
+ const bucketId = telemetryService.getBucketForDistinctId("user-1");
+ const streamKey = `telemetry-agg-stream:${PostHogEventTypes.SecretPulled}:${bucketId}`;
+
+ keyStore.streamTrim.mockImplementation(async (key, _minId, inclusive) => {
+ if (key === streamKey && inclusive === undefined) throw new Error("redis hiccup");
+ return 0;
+ });
+ keyStore.streamCollect.mockImplementation(async (key) =>
+ key === streamKey ? collectResult([pulledEvent()], "3-0") : { entries: [], lastId: null }
+ );
+
+ await telemetryService.processAggregatedEvents();
+
+ expect(postHogClient.capture).toHaveBeenCalledTimes(1);
+ expect(drainTrims(keyStore)).toEqual([[streamKey, "3-0", true]]);
+ });
});
diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.ts
index fd682bf0ac..cefb65e437 100644
--- a/backend/src/services/telemetry/telemetry-service.ts
+++ b/backend/src/services/telemetry/telemetry-service.ts
@@ -53,6 +53,7 @@ const TELEMETRY_BUCKET_NAMES = Array.from(
const TELEMETRY_EVENT_STREAM_BATCH_SIZE = 10_000;
const TELEMETRY_EVENT_STREAM_COLLECT_CEILING = 50_000;
const TELEMETRY_EVENT_STREAM_MAX_ENTRIES = 100_000;
+const TELEMETRY_EVENT_STREAM_RETENTION_MS = 30 * 60 * 1000;
type AggregatedEventData = Record<string, unknown>;
type SingleEventData = {
@@ -565,6 +566,12 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
const streamKey = KeyStorePrefixes.TelemetryAggregatedEventStream(eventType, bucketId);
+ try {
+ await keyStore.streamTrim(streamKey, `${Date.now() - TELEMETRY_EVENT_STREAM_RETENTION_MS}-0`);
+ } catch (error) {
+ logger.error(error, `Failed to apply retention trim to bucket ${bucketId} for ${eventType}`);
+ }
+
try {
const { entries, lastId } = await keyStore.streamCollect(
streamKey,
@@ -576,7 +583,7 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme
if (entries.length >= TELEMETRY_EVENT_STREAM_COLLECT_CEILING) {
logger.warn(
- `Telemetry aggregation hit the collection ceiling for bucket ${bucketId} of ${eventType} [collected=${entries.length}] [ceiling=${TELEMETRY_EVENT_STREAM_COLLECT_CEILING}] [maxLen=${TELEMETRY_EVENT_STREAM_MAX_ENTRIES}] — the shard is backing up; once it exceeds the MAXLEN cap the oldest entries are dropped`
+ `Telemetry aggregation hit the collection ceiling for bucket ${bucketId} of ${eventType} [collected=${entries.length}] [ceiling=${TELEMETRY_EVENT_STREAM_COLLECT_CEILING}] [maxLen=${TELEMETRY_EVENT_STREAM_MAX_ENTRIES}] — the shard is backing up; the excess is dropped once it ages past the retention window or the stream hits its MAXLEN cap`
);
}