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
fix flush
Thiago Araujo da Silva61af22b7e973
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex cc9c6d31c5..3879b6547a 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -423,7 +423,10 @@ 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 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.+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. **Two posthog-node behaviours make that flush work, and removing either silently breaks the guarantee without failing a test:**++- **`capture()` does not enqueue inline.** It resolves a promise chain first (`prepareEventMessage(...).then(...)`), so in the tick the capture loop ends the SDK's queue is still empty, `_flush()` returns at `if (!queue.length)`, and `flush()` resolves *successfully having sent nothing* — after which the drain trims. Delivery would then happen, if at all, on the SDK's own 10s interval, so a restart or a failing PostHog inside that window loses the batch instead of retrying it next tick. The drain therefore yields a macrotask (`settleCapturedEvents`) between the last `capture` and the `flush`. Awaiting the publish is not enough: the chain is several hops deep, and only a full macrotask yield drains it regardless of depth.+- **The queue defaults to 1000 entries and evicts the *oldest* on overflow**, logged at `info`. A drain enqueues one event per aggregation group with nothing draining in between, so the default drops the front of any shard that aggregates past it. The client is constructed with `maxQueueSize` sized to the collect ceiling × `BUCKET_CONCURRENCY`. Do not switch to `captureImmediate` to sidestep this: it POSTs one event per call (~200k requests where batching sends ~2k) and swallows delivery errors, so the drain would lose its only failure signal. 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 5d5d7f23ef..6b4b229c2a 100644--- a/backend/src/services/telemetry/telemetry-service.test.ts+++ b/backend/src/services/telemetry/telemetry-service.test.ts@@ -53,10 +53,14 @@ vi.mock("@app/lib/telemetry/metrics", () => ({TelemetryAggregationDropReason: { Retention: "retention", Unparseable: "unparseable" }}));+// eslint-disable-next-line import/first+import { PostHog } from "posthog-node";+// eslint-disable-next-line import/firstimport { POSTHOG_AGGREGATED_EVENTS, telemetryServiceFactory } from "./telemetry-service";const RETENTION_MS = 30 * 60 * 1000;+const COLLECT_CEILING = 50_000;const KEY_TTL_SECONDS = 60 * 60;const BUCKET_COUNT = 30;const SHARD_COUNT = POSTHOG_AGGREGATED_EVENTS.length * BUCKET_COUNT;@@ -471,6 +475,39 @@ describe("telemetry aggregated event storage", () => {});});+ // capture() enqueues on a later turn of the event loop, so a flush issued in the same tick as the+ // capture loop finds an empty queue and sends nothing, while reporting success to a drain that then+ // trims. Awaiting the publish is not enough: only yielding past the pending work drains it, which is+ // what the deferred capture here stands in for.+ test("lets the captures settle before the flush that gates the trim", async () => {+ const { keyStore, telemetryService } = createHarness();+ let captureSettled = false;+ let flushSawSettledCaptures = false;++ keyStore.streamCollect.mockResolvedValueOnce(collectResult([pulledEvent()], "3-0"));+ postHogClient.capture.mockImplementation(() => {+ setImmediate(() => {+ captureSettled = true;+ });+ });+ postHogClient.flush.mockImplementation(async () => {+ flushSawSettledCaptures = captureSettled;+ });++ await telemetryService.processAggregatedEvents();++ expect(flushSawSettledCaptures).toBe(true);+ expect(drainTrims(keyStore)).toHaveLength(1);+ });++ // The SDK defaults to 1000 queued events and drops the OLDEST on overflow, logged at info only.+ test("sizes the client queue for what one drain cycle can enqueue", () => {+ createHarness();++ const [, options] = vi.mocked(PostHog).mock.calls[0] as [string, { maxQueueSize?: number }];+ expect(options.maxQueueSize).toBeGreaterThanOrEqual(COLLECT_CEILING);+ });+test("skips the backlog round trip when nothing will export it", async () => {const { keyStore, telemetryService } = createHarness();const bucketId = telemetryService.getBucketForDistinctId("user-1");diff --git a/backend/src/services/telemetry/telemetry-service.ts b/backend/src/services/telemetry/telemetry-service.tsindex 8600fbdecb..217f85146d 100644--- a/backend/src/services/telemetry/telemetry-service.ts+++ b/backend/src/services/telemetry/telemetry-service.ts@@ -62,6 +62,9 @@ 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;const TELEMETRY_EVENT_STREAM_KEY_TTL_SECONDS = 60 * 60;+const BUCKET_CONCURRENCY = 2;++const TELEMETRY_POSTHOG_MAX_QUEUE_SIZE = TELEMETRY_EVENT_STREAM_COLLECT_CEILING * BUCKET_CONCURRENCY;type AggregatedEventData = Record<string, unknown>;type SingleEventData = {@@ -83,6 +86,11 @@ export type TTelemetryServiceFactoryDep = {emailDomainDAL: Pick<TEmailDomainDALFactory, "find">;};+const settleCapturedEvents = () =>+ new Promise<void>((resolve) => {+ setImmediate(resolve);+ });+const getBucketForDistinctId = (distinctId: string): string => {// Use SHA-256 hash for consistent distributionconst hash = crypto.nativeCrypto.createHash("sha256").update(distinctId).digest("hex");@@ -156,7 +164,10 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme}const postHog = appCfg.TELEMETRY_ENABLED- ? new PostHog(appCfg.POSTHOG_PROJECT_API_KEY, { host: appCfg.POSTHOG_HOST })+ ? new PostHog(appCfg.POSTHOG_PROJECT_API_KEY, {+ host: appCfg.POSTHOG_HOST,+ maxQueueSize: TELEMETRY_POSTHOG_MAX_QUEUE_SIZE+ }): undefined;// used for email marketting email sending purpose@@ -644,6 +655,8 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environmeawait publishAggregatedEvents(eventType, events, orgsIdentifyAttempted);+ await settleCapturedEvents();+await postHog.flush();await keyStore.streamTrim(streamKey, lastId, true);@@ -659,8 +672,6 @@ To opt into telemetry, you can set "TELEMETRY_ENABLED=true" within the environme}};- const BUCKET_CONCURRENCY = 2;-const processAggregatedEvents = async () => {if (!postHog) return;