Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
flush before trim
Thiago Araujo da Silva2fe69740c90b
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 7b61d97053..2a14cd31fc 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -421,7 +421,7 @@ 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. 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. That ceiling bounds the footprint of one shard; `BUCKET_CONCURRENCY` bounds how many of them are in flight, so the two multiply and both have to stay low. Raising either buys wall-clock the run does not need, since it is Redis-RTT-bound over 240 mostly-small shards and finishes well inside the cron's 8-minute handler timeout.+Draining is at-least-once: a shard is trimmed (`XTRIM MINID`) only after the PostHog client has *delivered* its batch, so a run that throws before that point retries the whole batch on the next tick. Handing the batch to `capture` is not delivery — that only enqueues it in the SDK's in-memory buffer, and the stream holds the only durable copy, so the drain awaits `flush()` before trimming. A rejected flush therefore costs a duplicated batch at worst, where trimming first would have lost it outright. 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. That ceiling bounds the footprint of one shard; `BUCKET_CONCURRENCY` bounds how many of them are in flight, so the two multiply and both have to stay low. Raising either buys wall-clock the run does not need, since it is Redis-RTT-bound over 240 mostly-small shards and finishes well inside the cron's 8-minute handler timeout.**Two independent bounds keep a shard from growing without limit, and both are load-bearing:**diff --git a/backend/src/services/telemetry/telemetry-service.test.ts b/backend/src/services/telemetry/telemetry-service.test.tsindex b75b939e35..44ee8f99b4 100644--- a/backend/src/services/telemetry/telemetry-service.test.ts+++ b/backend/src/services/telemetry/telemetry-service.test.ts@@ -29,6 +29,7 @@ const postHogClient = {capture: vi.fn(),groupIdentify: vi.fn(),identify: vi.fn(),+ flush: vi.fn(async () => undefined),shutdown: vi.fn(async () => undefined)};@@ -193,6 +194,41 @@ describe("telemetry aggregated event storage", () => {expect(drainTrims(keyStore)).toHaveLength(0);});+ test("confirms delivery with the SDK before trimming the drained entries", async () => {+ const { keyStore, telemetryService } = createHarness();+ const order: string[] = [];++ keyStore.streamCollect.mockResolvedValueOnce(collectResult([pulledEvent()], "3-0"));+ postHogClient.capture.mockImplementation(() => {+ order.push("capture");+ });+ postHogClient.flush.mockImplementation(async () => {+ order.push("flush");+ });+ keyStore.streamTrim.mockImplementation(async (_key, _minId, inclusive) => {+ if (inclusive) order.push("trim");+ return 0;+ });++ await telemetryService.processAggregatedEvents();++ // `capture` only enqueues in memory, so trimming before the flush resolves would drop the only+ // durable copy of the batch while it is still undelivered.+ expect(order).toEqual(["capture", "flush", "trim"]);+ });++ test("leaves the shard untrimmed when the delivery flush fails, so the batch is retried", async () => {+ const { keyStore, telemetryService } = createHarness();++ keyStore.streamCollect.mockResolvedValueOnce(collectResult([pulledEvent()]));+ postHogClient.flush.mockRejectedValueOnce(new Error("posthog batch rejected"));++ await telemetryService.processAggregatedEvents();++ expect(postHogClient.capture).toHaveBeenCalledTimes(1);+ expect(drainTrims(keyStore)).toHaveLength(0);+ });+test("skips an unparseable entry rather than dropping the whole shard", async () => {const { keyStore, telemetryService } = createHarness();diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.tsindex 7fcd530dc2..1483b1a78d 100644--- a/backend/src/services/telemetry/telemetry-service.ts+++ b/backend/src/services/telemetry/telemetry-service.ts@@ -607,6 +607,8 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmeawait publishAggregatedEvents(eventType, events, orgsIdentifyAttempted);+ await postHog.flush();+await keyStore.streamTrim(streamKey, lastId, true);logger.info(`Processed ${events.length} events from bucket ${bucketId} for ${eventType}`);